JavaScript 和 Python 的语法对比

1. Variables

FeatureJavaScriptPython
Declarationvar, let, constNo specific keyword, just assignment
ScopeFunction scope (var), block scope (let, const)Block scope (indented code block)
HoistingVariables declared with var are hoistedNo hoisting
ConstantsconstCONSTANT_NAME convention, no true constant

2. Data Types

TypeJavaScriptPython
PrimitivesNumber, String, Boolean, undefined, null, Symbolint, float, str, bool, None
ObjectsObject, Array, Function, Date, etc.Lists, Tuples, Sets, Dictionaries, etc.
Type Checkingtypeof operatortype() function

3. Numbers

FeatureJavaScriptPython
TypesOne number type (floating-point)int, float
PrecisionDouble precision floating-pointArbitrary precision for int, double precision for float
Special ValuesNaN, Infinitymath.nan, math.inf
Integer DivisionAlways floating-pointInteger division with //, floating-point with /

4. Casting

OperationJavaScriptPython
String to NumberNumber("3.14")float("3.14") or int("3")
Number to StringString(3.14)str(3.14)
Boolean ConversionBoolean(value)bool(value)

5. Operators

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

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

6. Lists

In JavaScript, these are called Arrays.

FeatureJavaScriptPython
Declarationlet arr = [1, 2, 3];lst = [1, 2, 3]
Accessarr[0]lst[0]
Sizearr.lengthlen(lst)
Add Elementarr.push(4)lst.append(4)
Remove Elementarr.pop()lst.pop()
Iterationarr.forEach((item) => {...})for item in lst: ...

7. Tuples

Tuples do not exist as such in JavaScript.

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

8. Sets

FeatureJavaScriptPython
Declarationlet set = new Set();st = set()
Add Elementset.add(value)st.add(value)
Remove Elementset.delete(value)st.discard(value)
Containsset.has(value)value in st
Sizeset.sizelen(st)
Iterationset.forEach((value) => {...})for value in st: ...

9. Dictionaries

In JavaScript, these are similar to Objects.

FeatureJavaScriptPython
Declarationlet obj = {key: 'value'};dict = {'key': 'value'}
Accessobj['key'] or obj.keydict['key']or dict.get('key')
Add/Updateobj['newKey'] = 'newValue';dict['newKey'] = 'newValue'
Removedelete obj['key'];del dict['key']
KeysObject.keys(obj)dict.keys()
ValuesObject.values(obj)dict.values()
Iterationfor (let key in obj) {...}for key in dict: ...

10. If…Else, while, for

Control StructureJavaScriptPython
If…Elseif (condition) {...} else {...}if condition: ... else: ...
Whilewhile (condition) {...}while condition: ...
Forfor (let i = 0; i < length; i++) {...}for i in range(length): ...
For-Eacharray.forEach((item) => {...})for item in iterable: ...

11. Functions

FeatureJavaScriptPython
Declarationfunction functionName(args) {...} or
const functionName = (args) => {...}
def function_name(args): ...
Returnreturn value;return value
Default Parametersfunction(a, b = 1) {...}def func(a, b=1): ...
Anonymous FunctionsArrow functions (args) => { ... }-

12. Classes

FeatureJavaScriptPython
Declarationclass ClassName {...}class ClassName: ...
Constructorconstructor(args) {...}def __init__(self, args): ...
Inheritanceclass Derived extends Base {...}class Derived(Base): ...
MethodsInside class block methodName(args) {...}Indentation-based def method_name(self, args): ...

13. Error Handling

FeatureJavaScriptPython
Try-Catchtry {...} catch (error) {...}try: ... except Exception as error: ...
Throw Errorthrow new Error('message');raise Exception('message')
Custom Error TypesExtend Error classExtend Exception class

14. Miscellaneous

FeatureJavaScriptPython
ModulesImport with import or requireimport module or from module import name
Async/AwaitAsynchronous programming with async/awaitAsynchronous programming with async/await
File I/OFile operations with Node.js fs moduleFile operations with open function
List ComprehensionNot available directly[expression for item in list if condition]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值