本文翻译☞https://es6.ruanyifeng.com/#docs/有改动
let 块级变量 const 块级常量
特点:
- 只在代码块中有效
{
let a = 3
}
console.log(a); //a is not defined
-
不存在变量提升
-
暂时性死区
var b = 233;
if (true) {
b = 1
let b;//Cannot access 'b' before initialization
}
如果是es5 var是可以的.
在代码块内,使用let命令声明变量之前,该变量都是不可用的。这在语法上,称为“暂时性死区”(temporal dead zone,简称 TDZ)
- 不许重重声明
注意:
for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc
- const
- 本质就是:
不是变量的值不得改动,而是变量指向的那个内存地址所保存的数据不得改动。
const obj = {
x: 1
}
obj.x = 2
console.log(obj);//{"x": 2}
变量的解构与赋值:
destructuring
- 谁可以解构赋值:只要某种数据结构具有 Iterator 接口(以后再写这个)
- 概念:“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
- 详细:
- 数组:
- 基本写法:
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
- 解构失败:变量的值就等于undefined,或者模式两边不相等。
let [bar, foo] = [1];
- 解构半成功:
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
var [a = 1, b = 2, c = 3] = [undefined, null, NaN]
console.log(a, b, c);//1,null,NaN
1.2 默认值是表达式:表达式是惰性的,只有用到时才会执行
function f() {
console.log('aaa');
}
let [x = f()] = [1];//x=1
function f() {
console.log('aaa');
return 2
}
//let [x = f()] = [1];
let [x = f()] = [undefined] //aaa
console.log(x); //2
1.3 默认值可以引用解构赋值的其他变量,但该变量必须已经声明。
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError: y is not defined
//因为他是顺序执行的所以x = undefined,执行x=y;而y=undefined
对象:
- 不安装顺序赋值,安装属性名赋值
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let {foo} = {bar: 'baz'};
foo // undefined
本质:
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc // Object {start: Object}
start // Object {line: 1, column: 5}
字符串
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o
let {length : len} = 'hello';
len // 5
Number和Boolean
- 先转成对象:
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
函数参数的解构赋值
- 传入参数一刻已经解构
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
注意
- undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
- 不要用已经声明的变量进行解构赋值,{x}像不像代码块
- 可对象对数组解构,但是反过来不行
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3