最基础:var声明

  1. function f(shouldInitialize: boolean) {
  2. if (shouldInitialize) {
  3. var x = 10;
  4. }
  5. return x;
  6. }
  7. f(true); // returns '10'
  8. f(false); // returns 'undefined'

明明在大括号外却能进行使用,就可能会导致函数声明重复,值互相覆盖,例子:

  1. //这里其实使用了同一个x
  2. function f(x) {
  3. var x;
  4. var x;
  5. if (true) {
  6. var x;
  7. }
  8. }
  1. for (var i = 0; i < 10; i++) {
  2. setTimeout(function() { console.log(i); }, 100 * i);
  3. }

let:块作用域

在catch语句里声明的变量也具有同样的作用域规则。

const:块作用域+不能被重新赋值(引用的值不可变)

解构数组

  1. let input = [1, 2];
  2. let [first, second] = input;
  3. console.log(first); // outputs 1
  4. console.log(second); // outputs 2

应用于函数:

  1. function f([first, second]: [number, number]) {
  2. console.log(first);
  3. console.log(second);
  4. }
  5. f(input);

…语法创建剩余变量

  1. let [first, ...rest] = [1, 2, 3, 4];
  2. console.log(first); // outputs 1
  3. console.log(rest); // outputs [ 2, 3, 4 ]
  1. let [first1] = [1, 2, 3, 4];
  2. let [, second, , fourth] = [1, 2, 3, 4];
  3. console.log(first1); // outputs 1

解构对象

  1. let o = {
  2. a: "foo",
  3. b: 12,
  4. c: "bar"
  5. };
  6. let { a, b } = o;

…语法创建剩余变量

  1. let o = {
  2. a: "foo",
  3. b: 12,
  4. c: "bar"
  5. };
  6. let { a, ...passthrough } = o;
  7. let total = passthrough.b + passthrough.c.length;

解构时,赋予默认值

  1. function keepWholeObject(wholeObject: { a: string, b?: number }) {
  2. let { a, b = 1001 } = wholeObject;
  3. }

解构时,指定类型

  1. let {a, b}: {a: string, b: number} = o;

函数申明解构

  1. type C = { a: string, b?: number }
  2. function f({ a, b }: C): void {
  3. // ...
  4. }
  1. function f({ a, b = 0 } = { a: "" }): void {
  2. // ...
  3. }
  4. f({ a: "yes" }); // ok, default b = 0
  5. f(); // ok, default to {a: ""}, which then defaults b = 0
  6. f({}); // error, 'a' is required if you supply an argument

展开

  1. let first = [1, 2];
  2. let second = [3, 4];
  3. let bothPlus = [0, ...first, ...second, 5];

这会令bothPlus的值为[0, 1, 2, 3, 4, 5]。 展开操作创建了 first和second的一份浅拷贝。 它们不会被展开操作所改变。
展开对象:

  1. let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
  2. let search = { ...defaults, food: "rich" };

1.像数组展开一样,它是从左至右进行处理,但结果仍为对象。 这就意味着出现在展开对象后面的属性会覆盖前面的属性 2.展开一个对象实例时,你会丢失其方法