2.变量声明

var   let   const  

1.

for (var i = 0; i < 10; i++) {

  setTimeout(

    function() { console.log(i); }

  , 100 * i);

执行结果为10 10 ....

for (var i = 0; i < 10; i++) {

  (function(i) {

    setTimeout(

      function() { console.log(i); }

    , 100 * i);

  })(i);

}(立即执行)

执行结果为1 2 3 ...

for (let i = 0; i < 10 ; i++) {

  setTimeout(

    function() {console.log(i); }

  , 100 * i);

}(每次迭代创建新的作用域)

2. var(函数作用域)  let(块作用域)

function f(shouldInitialize: boolean) {

  if (shouldInitialize) {

    var x = 10;

  }

  return x;

}

f(true); // returns '10'

f(false); // returns 'undefined'

 

function f(input: boolean) {

  let a = 100;

  if (input) {

    let b = a + 1;

    return b;

  }

  return b;// Error: 'b' doesn't exist here

}

a++; // illegal to use 'a' before it's declared;(暂时性死区)

let a;

 function sumMatrix(matrix: number[][]) {

  let sum = 0;

  for (let i = 0; i < matrix.length; i++){

    var currentRow = matrix[i];

    for (let i = 0; i < currentRow.length; i++){

      sum += currentRow[i];(屏蔽之前的i)

    }

  }

  return sum;

}

3.解构,展开

解构

let [first, second] = [1, 2]  // first 1  second 2

let [first, ...rest] = [1, 2, 3, 4]  // first 1  rest 2, 3, 4

// 对象解构相同

属性重命名: let o = { a: "foo", b: 12, c: "bar" };  let { a: newName1, b: newName2 } = o;

展开

let first = [1, 2];

let second = [3, 4];

let bothPlus = [0, ...first, ...second, 5];

// 对象展开相同

 

上一篇:EF框架


下一篇:uva11292