这是本系列笔记的第5篇!
让学习“上瘾”,成为更好的自己!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数组的解构赋值</title>
</head>
<body>
<script>
// 1, 基本用法
// 解构 --> ES6允许按照一定模式从数组和对象中提取值,然后对变量进行赋值
// 以前,为变量赋值只能直接指定值
// let a = 12;
// let b = 232;
// (2) ES6写法 --> “模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值
// let [a, b] = [12, 232];
// console.log(a, b);
// (3) 嵌套数组的解构
// let [foo, [[bar], baz]] = [1, [[2], 9]];
// console.log(foo);
// console.log(bar);
// let [x, , y] = [1, ,3];
// console.log(y);
// let [head, ...tail] = [1, 3, 4, 5];
// console.log(tail);
// let [x, y, ...z] = ['a'];
// console.log(x); // 'a'
// console.log(y); // undefined
// console.log(z); // []
// (3) 解构失败 --> 等号左边的模式与右边的数组完全不匹配 || 左边的模式匹配范围大于右边数组的范围
// 如果解构失败(理解为“模式不匹配”),变量的值就等于undefined
// let [foo] = [];
// let [bar, foo] = [1];
// 以上两种情况均属于结构不成功,foo的值都会等于undefined
// (4) 解构不完全 --> 等号左边的模式只匹配一部分等号右边的数组
// let [aa] = [2, 31, 1];
// console.log(aa); // 2
// let [a, [b], c] = [12, [2, 1], 90];
// console.log(b); // 2
// (5) 如果等号右边不是数组(严格地说不是可遍历的解构,见15章),则会报错
// 以下4个语句都会报错 --> 等号右边的值转为对象都不具备Iterator接口(前三个语句),或者本身就不具备Iterator接口(最后一个语句)
// let [foo] = 1;
// let [foo1] = false;
// let [foo2] = NaN;
// //
// let [foo3] = {};
//
// (6) 对于Set结构(数据结构具有Iterator接口)
// let [a, b, c] = new Set(['af', 'dfa', 'er']);
// console.log(a);
// (7) 数据结构具有Iterator接口,都可以采用数组形式的解构赋值
// function* fibs(){ // fibs是一个Generator函数(16章)
// let a = 0;
// let b = 1;
// while (true){
// yield a;
// [a, b] = [b, a + b];
// }
// }
// let [first, second, third, fourth] = fibs();
// console.log(second); // 1
// console.log(fourth); // 2
// 2,默认值
// (1)
// let [foo = true] = [];
// console.log(foo);
// let [x, y = 'b'] = ['a'];
// console.log(x); // 'a'
// console.log(y); // 'b'
// let [x, y = 'b'] = ['a', undefined];
// console.log(x); // 'a'
// console.log(y); // 'b'
// 【注意】
// (2) ES6内部使用严格相等运算符(===)判断一个位置是否有值,所以,如果一个数组成员不严格等于undefined,默认值是不会生效
let [x = 1] = [null];
console.log(x); // null
// 如果一个数组成员是null, 默认值是不会生效的,因为null不严格等于undefined
// (3) 如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到时才会求值
function f(){
console.log('aaa');
}
let [x = f()] = [1]; // 因为x能取到值,所以函数f根本不会执行
let x;
if ([1][0] === undefined) {
x = f();
} else {
x = [1][0];
}
// (4) 默认值可以引用解构赋值的其他变量,但该变量必须已经声明
let [x=1, y=x] = []; // x = 1, y = x
let [x=1, y=x] = [2]; // x = 2, y = 2
let [x = 1, y = x] = [1, 3]; // x = 1, y = 3
let [x = y, y = 1] = []; // 报错 --> 因为x用到默认值y时,y还没有声明
</script>
</body>
</html>