test haha

Refer to Ruan Yifeng ES6

let

Variables are not promoted

letThere is no variable promotion for the declared variable. You can only complete the declaration first and then use it, otherwise an error will be reported.

console.log(a); // undefined
console.log(b); // Uncaught ReferenceError: b is not defined
var a = 1;      
let b = 2;

Only valid within the current code block

letThe declared variable is only letvalid within the code block where the command is located

if (true) { var a = 2; let b = 3 };
console.log(a); // 2
console.log(b); // Uncaught ReferenceError: b is not defined
var a = [];
for (var i = 0; i < 5; i++) {
  a[i] = function () { console.log(i); }
}
// 这里的i都指向全局变量i
a[2]();         // 5
a[4]();         // 5
console.log(i); //5

var b = [];
for (let k = 0; k < 5; k++) {
  b[k] = function () { console.log(k); }
}
// k是用let声明的,每循环一次等于重新声明一次k,js引擎会记住上次k的值,在这个值的基础上进行计算
b[2]();         // 2
b[4]();         // 4
console.log(k); // Uncaught ReferenceError: k is not defined

//for循环的()内是父作用域,{}内是子作用域
for (var v = 0; v < 2; v++) {
  let v = 'h';
  console.log(v);
}
// h
// h
// h

Duplicate declarations are not allowed

letRepeated declaration of the same variable in the same scope is not allowed

function func() {
  let a = 2;
  let a = 6;
}
func()  // Uncaught SyntaxError: Identifier 'a' has already been declared

const

Declared constants are read-only

constDeclare a read-only constant, once declared, the constant pointed to 内存地址cannot be changed

For 基本数据类型, it is immutable

const a = 2;
a = 3;      // Uncaught TypeError: Assignment to constant variable.

For 对象或数组等复杂数据类型, it is 指针immutable

const a = { num: 2 };
const b = [1];
a.num = 3;    // 不报错,内存地址未变
b[0] = 'hi';  // 不报错,内存地址未变
a = {};       // Uncaught TypeError: Assignment to constant variable  

The declaration must be assigned at the same time

constWhen declaring a constant, you must assign a value, and you cannot leave it for later assignment

const a;
a = 2;  //Uncaught SyntaxError: Missing initializer in const declaration

constThe same letas, can only be declared before use, and only valid in the block-level scope where the declaration is located

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382062&siteId=291194637