学习了ES6和Python,发现二者语法实在相识。
注:以下代码用到ES6。可用node.js环境验证。
while
ESlet i = 1;
while (true){
i ++;
if(i >10){
break
}
}
console.log(i)
Pythoni = 1
while True:
i += 1
if i > 10:
break
print(i)
迭代器
iterator
ES6let list = [1,2,3,4];
let iter = list[Symbol.iterator]();
console.log(iter.next().value);
console.log(iter.next().value);
Pythonlist = [1,2,3,4]
it = iter(list)
print(next(it))
print(next(it))
yield
ES6function * fibonacci(n){
let [a, b, counter] = [0, 1, 0];
while (true){
if (counter > n){
return
}
yield a;
[a, b] = [b, a + b];
counter += 1;
}
}
f = fibonacci(10);
while(true){
let item = f.next();
if(item.done){
break;
}
console.log(item.value);
}
Python#!/usr/bin/python3
import sys
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
数组推导
Pythonvec = [2, 4, 6]
result = [[x, x**2] for x in vec]
print(result)
ES6let vec = [2, 4, 6];
let result = vec.map(arr =>{
return [arr,arr**2];
});
console.log(result);
ES7let vec = [2, 4, 6];
let result = [for(i of vec) i**2];
console.log(result);
删除列表元素
Pythonvec = [-1, 1, 66.25, 333, 333, 1234.5]
del vec[3:4]
print(vec)
ESlet vec = [-1, 1, 66.25, 333, 333, 1234.5];
vec.splice(3, 4 - 3);
console.log(vec);
集合
Pythonbasket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
ES6let basket = new Set(['apple', 'orange', 'apple', 'pear', 'orange', 'banana']);
console.log(basket);
字典
Pythondict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
print(dict)
ES6let dict = new Map([['Alice','2341'], ['Beth', '9102'], ['Cecil', '3258']]);
console.log(dict);