主题
Python ↔ JavaScript 速查表
语法与对象
| 场景 | JavaScript / TypeScript | Python |
|---|---|---|
| 输出 | console.log(x) | print(x) |
| 变量 | let x = 1 | x = 1 |
| 空值 | null | None |
| 布尔值 | true / false | True / False |
| 模板字符串 | `hi ${name}` | f"hi {name}" |
| 逻辑运算 | && / || / ! | and / or / not |
| 条件表达式 | ok ? a : b | a if ok else b |
| 判等 | a === b | a == b(不完全等价) |
| 判空 | x === null | x is None |
| 长度 | items.length | len(items) |
| 尾项 | items.at(-1) | items[-1] |
| 切片 | items.slice(0, 3) | items[:3] |
| 添加 | items.push(x) | items.append(x) |
| 合并列表 | [...a, ...b] | [*a, *b] 或 a + b |
| 合并字典 | {...a, ...b} | {**a, **b} |
| 包含 | items.includes(x) | x in items |
| 对象键 | Object.keys(obj) | obj.keys() |
| 对象条目 | Object.entries(obj) | obj.items() |
| 安全取键 | obj.key ?? fallback | obj.get("key", fallback)(仅缺键才回退) |
| JSON 解析 | JSON.parse(text) | json.loads(text) |
| JSON 序列化 | JSON.stringify(obj) | json.dumps(obj) |
| 类型查询 | typeof x | type(x) |
集合处理
python
users = [{"name": "Lin", "age": 25}, {"name": "Mo", "age": 16}]
# filter + map
names = [u["name"] for u in users if u["age"] >= 18]
# find,第一个符合条件的,没找到返回 None
first = next((u for u in users if u["age"] >= 18), None)
# reduce 求和
age_total = sum(u["age"] for u in users)
# 不改变原列表的排序
ordered = sorted(users, key=lambda u: u["age"])
# 带索引遍历
for i, user in enumerate(users):
print(i, user["name"])函数与异步
python
def greet(name: str = "朋友") -> str:
return f"你好,{name}"
params = {"name": "Lin"}
print(greet(**params)) # 关键字参数展开
import asyncio
async def main():
await asyncio.sleep(0.1)
asyncio.run(main()) # 普通脚本中的事件循环入口Python 的 async 函数调用得到协程,需调度或 await 才执行。不要把协程等同于自动启动的 Promise。
包管理
| npm/pnpm | uv |
|---|---|
npm init | uv init --python 3.12 |
npm install pkg | uv add pkg |
npm install -D pkg | uv add --dev pkg |
npm ci | uv sync --locked |
node main.js | uv run main.py |
npx tool | uvx tool |
package.json | pyproject.toml |
| lockfile | uv.lock |
最常踩的五个坑
- dict 用
obj["key"],不是.key;SDK 对象则可能有属性。 - 空 list/dict 在 Python 是假,JS 的空数组/对象是真。
- 类型注解不自动执行运行时校验,用 Pydantic 验证不可信数据。
- 可变默认参数会共享状态,用
None在函数内创建。 - 文件路径相对当前工作目录;脚本旁的文件使用
Path(__file__)。