PyPyBridge

语法与数据结构速通

const/let 消失、undefined 消失、数组方法变推导式、对象字面量变 dict。

14 分钟 · 右栏代码可点击「运行」


变量与真值

JavaScript
1const name = "Ada";
2let count = 0;
3count++;
4
5const s = `Hi ${name}`;
6if (!items.length) { ... }
7x === undefined || x === null;
Python
1name = "Ada" # 没有声明关键字,赋值即定义
2count = 0
3count += 1 # 没有 ++
4
5s = 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 = items
2 .filter(i => i.length > 3)
3 .map(i => i.toUpperCase());
4
5const 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]
2
3total = 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。

练一练

这张卡的示例代码已在游乐场中备好,改一改再运行。

在游乐场中打开