JS、Python对比学习

原文链接:http://www.jianshu.com/p/90c77da64b44

条件运算符(三目)

# Python:
a = 1
b = 2
h = a-b if a>b else a+b
# h = 3

# JS:
var a = 1,b=2
h = a>b?a-b:b+a
# h = 3

遍历列表

# JS:
const js_list = ["t","ty","ui","op"]
for(let i of js_list){
  console.log(i)
}
# 输出:
t
ty
ui
op

for(let i in js_list){
  console.log(i)
}
# 输出:
0
1
2
3

# Python:
a = [1,2,3,4,5]
for i in a:
  print(i)
# 输出:
1
2
3
4
5

JS中的箭头函数和Python中的lambda函数有点相似,以下的js、python都是一个函数,还没被调用

# JS:
const js = x => x+1
console.log(js(100)) // 101

# Python
python = lambda x:x+1
print(python(100))  // 101

字符模板:python在3.6之后引入了f""字符模板,类似js中的``模板:

# python :
test = "test !"
print(f"this is a {test}") 
# 输出:this is a test !
# js
const test = "test!" 
console.log(`this is a ${test}`)
# 输出:this is a test !
展开阅读全文
博主设置当前文章不允许评论。