JavaScript 和 Python 的语法对比

1. Variables

Feature JavaScript Python
Declaration var, let, const No specific keyword, just assignment
Scope Function scope (var), block scope (let, const) Block scope (indented code block)
Hoisting Variables declared with var are hoisted No hoisting
Constants const CONSTANT_NAME convention, no true constant

2. Data Types

Type JavaScript Python
Primitives Number, String, Boolean, undefined, null, Symbol int, float, str, bool, None
Objects Object, Array, Function, Date, etc. Lists, Tuples, Sets, Dictionaries, etc.
Type Checking typeof operator type() function

3. Numbers

Feature JavaScript Python
Types One number type (floating-point) int, float
Precision Double precision floating-point Arbitrary precision for int, double precision for float
Special Values NaN, Infinity math.nan, math.inf
Integer Division Always floating-point Integer division with //, floating-point with /

4. Casting

Operation JavaScript Python
String to Number Number("3.14") float("3.14") or int("3")
Number to String String(3.14) str(3.14)
Boolean Conversion Boolean(value) bool(value)

5. Operators

In JavaScript, ** is available in ECMAScript 2016 (ES7).

Operator Type JavaScript Python
Arithmetic +, -, *, /, %, ** Same, // for integer division
Comparison ==, ===, !=, !==, <, >, <=, >= ==, !=, <, >, <=, >=
Logical &&, ||, ! and, or, not
Ternary condition ? true : false true if condition else false

6. Lists

In JavaScript, these are called Arrays.

Feature JavaScript Python
Declaration let arr = [1, 2, 3]; lst = [1, 2, 3]
Access arr[0] lst[0]
Size arr.length len(lst)
Add Element arr.push(4) lst.append(4)
Remove Element arr.pop() lst.pop()
Iteration arr.forEach((item) => {...}) for item in lst: ...

7. Tuples

Tuples do not exist as such in JavaScript.

Feature JavaScript Python
Declaration - tup = (1, 2, 3)
Immutability - Immutable
Access - tup[0]
Size - len(tup)

8. Sets

Feature JavaScript Python
Declaration let set = new Set(); st = set()
Add Element set.add(value) st.add(value)
Remove Element set.delete(value) st.discard(value)
Contains set.has(value) value in st
Size set.size len(st)
Iteration set.forEach((value) => {...}) for value in st: ...

9. Dictionaries

In JavaScript, these are similar to Objects.

Feature JavaScript Python
Declaration let obj = {key: 'value'}; dict = {'key': 'value'}
Access obj['key'] or obj.key dict['key']or dict.get('key')
Add/Update obj['newKey'] = 'newValue'; dict['newKey'] = 'newValue'
Remove delete obj['key']; del dict['key']
Keys Object.keys(obj) dict.keys()
Values Object.values(obj) dict.values()
Iteration for (let key in obj) {...} for key in dict: ...

10. If…Else, while, for

Control Structure JavaScript Python
If…Else if (condition) {...} else {...} if condition: ... else: ...
While while (condition) {...} while condition: ...
For for (let i = 0; i < length; i++) {...} for i in range(length): ...
For-Each array.forEach((item) => {...}) for item in iterable: ...

11. Functions

Feature JavaScript Python
Declaration function functionName(args) {...} or
const functionName = (args) => {...}
def function_name(args): ...
Return return value; return value
Default Parameters function(a, b = 1) {...} def func(a, b=1): ...
Anonymous Functions Arrow functions (args) => { ... } -

12. Classes

Feature JavaScript Python
Declaration class ClassName {...} class ClassName: ...
Constructor constructor(args) {...} def __init__(self, args): ...
Inheritance class Derived extends Base {...} class Derived(Base): ...
Methods Inside class block methodName(args) {...} Indentation-based def method_name(self, args): ...

13. Error Handling

Feature JavaScript Python
Try-Catch try {...} catch (error) {...} try: ... except Exception as error: ...
Throw Error throw new Error('message'); raise Exception('message')
Custom Error Types Extend Error class Extend Exception class

14. Miscellaneous

Feature JavaScript Python
Modules Import with import or require import module or from module import name
Async/Await Asynchronous programming with async/await Asynchronous programming with async/await
File I/O File operations with Node.js fs module File operations with open function
List Comprehension Not available directly [expression for item in list if condition]