最基础:var声明
function f(shouldInitialize: boolean) {if (shouldInitialize) {var x = 10;}return x;}f(true); // returns '10'f(false); // returns 'undefined'
明明在大括号外却能进行使用,就可能会导致函数声明重复,值互相覆盖,例子:
//这里其实使用了同一个xfunction f(x) {var x;var x;if (true) {var x;}}在
for (var i = 0; i < 10; i++) {setTimeout(function() { console.log(i); }, 100 * i);}
let:块作用域
在catch语句里声明的变量也具有同样的作用域规则。
const:块作用域+不能被重新赋值(引用的值不可变)
解构数组
let input = [1, 2];let [first, second] = input;console.log(first); // outputs 1console.log(second); // outputs 2
应用于函数:
function f([first, second]: [number, number]) {console.log(first);console.log(second);}f(input);
…语法创建剩余变量
let [first, ...rest] = [1, 2, 3, 4];console.log(first); // outputs 1console.log(rest); // outputs [ 2, 3, 4 ]
let [first1] = [1, 2, 3, 4];let [, second, , fourth] = [1, 2, 3, 4];console.log(first1); // outputs 1
解构对象
let o = {a: "foo",b: 12,c: "bar"};let { a, b } = o;
…语法创建剩余变量
let o = {a: "foo",b: 12,c: "bar"};let { a, ...passthrough } = o;let total = passthrough.b + passthrough.c.length;
解构时,赋予默认值
function keepWholeObject(wholeObject: { a: string, b?: number }) {let { a, b = 1001 } = wholeObject;}
解构时,指定类型
let {a, b}: {a: string, b: number} = o;
函数申明解构
type C = { a: string, b?: number }function f({ a, b }: C): void {// ...}
function f({ a, b = 0 } = { a: "" }): void {// ...}f({ a: "yes" }); // ok, default b = 0f(); // ok, default to {a: ""}, which then defaults b = 0f({}); // error, 'a' is required if you supply an argument
展开
let first = [1, 2];let second = [3, 4];let bothPlus = [0, ...first, ...second, 5];
这会令bothPlus的值为[0, 1, 2, 3, 4, 5]。 展开操作创建了 first和second的一份浅拷贝。 它们不会被展开操作所改变。
展开对象:
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };let search = { ...defaults, food: "rich" };
1.像数组展开一样,它是从左至右进行处理,但结果仍为对象。 这就意味着出现在展开对象后面的属性会覆盖前面的属性 2.展开一个对象实例时,你会丢失其方法
