本文只介绍了在ES2015与TypeScript之间变量声明, 解构赋值的区别和新增
如果你不熟悉怎么使用let和const还有解构赋值,请参考阮大神的ES6教程
如果你不清楚为什么不使用var.请参考官方文档http://www.typescriptlang.org/docs/handbook/variable-declarations.html#variable-declarations 的Variable Declarations 章节
let
1.需要先声明变量后使用。在ES2015运行时会报错,但是目前TypeScript不会
function foo() {
// okay to capture 'a'
return a;
}
// illegal call 'foo' before 'a' is declared
// ES2015 runtimes should throw an error here
foo();
let a;
2.同一个作用域多次声明同一个变量; ES2015:会使用最后那个变量; TypeScript:不允许
let x = 10;
let x = 20; // error: can't re-declare 'x' in the same scope
function f(x) {
let x = 100; // error: interferes with parameter declaration
}
function g() {
let x = 100;
var x = 100; // error: can't have both declarations of 'x'
}
不同域是允许的(ES2015 & TypeScript)
function f(condition, x) {
if (condition) {
let x = 100;
return x; // 属于if 块级作用域
}
return x; //属于function f () 作用域
}
f(false, 0); // returns '0'
f(true, 0); // returns '100'
嵌套域是允许的(ES2015 & TypeScript)
function sumMatrix(matrix: number[][]) {
let sum = 0;
for (let i =