语法与数据结构速通
const/let 消失、undefined 消失、数组方法变推导式、对象字面量变 dict。
14 分钟 · 右栏代码可点击「运行」
变量与真值
JavaScript
1const name = "Ada";2let count = 0;3count++;45const s = `Hi ${name}`;6if (!items.length) { ... }7x === undefined || x === null;
Python
1name = "Ada" # 没有声明关键字,赋值即定义2count = 03count += 1 # 没有 ++45s = f"Hi {name}"6if not items: # 空列表/空串/0/None 全是假值7x is None # 只有 None,没有 undefined;判空用 is
==在 Python 里近似 JS 的===(不同类型比较直接返回 False),没有强制转换的坑。- 真值判断比 JS 更激进:
[]、""、0、{}、None都是假值。if not xs:是地道写法。
数组方法 → 推导式
JavaScript
1const upper = items2 .filter(i => i.length > 3)3 .map(i => i.toUpperCase());45const total = nums.reduce((a, b) => a + b, 0);6const first = users.find(u => u.ok);7const any = users.some(u => u.ok);
Python
1upper = [i.upper() for i in items if len(i) > 3]23total = sum(nums) # 常见 reduce 已内建4first = next(u for u in users if u.ok)5any_ok = any(u.ok for u in users) # 还有 all()
- 没有链式方法的 Python 用推导式 + 内建函数组合:sum / max / min / sorted / any / all 覆盖绝大多数 reduce 场景。
- spread:
[...a, ...b]→[*a, *b];{...a, ...b}→{**a, **b}或a | b(3.9+)。
对象字面量 → dict
JavaScript
1const cfg = { host: "0.0.0.0", port: 8000 };2cfg.port;3cfg.timeout ?? 30;4delete cfg.host;5Object.keys(cfg);
Python
1cfg = {"host": "0.0.0.0", "port": 8000}2cfg["port"] # 点号取值是属性,dict 只有下标3cfg.get("timeout", 30) # ?? 的近似物(注意 0 也是"有值")4del cfg["host"]5list(cfg) # 迭代 dict 默认得到键
- JSON.parse / JSON.stringify →
json.loads/json.dumps。dataclass + Pydantic 承担 TS 类型那一层。 - 真想用点号访问:
types.SimpleNamespace或 dataclass。但惯例是 dict 保持 dict。
练一练
这张卡的示例代码已在游乐场中备好,改一改再运行。