// 赋值 根据位置对应关系赋值 模式匹配
let [x,y,z] = [1,2,3]; console.log(x+"--"+y+"---"+z); // 1--2--3
// 以后都不会成功 每一模式匹配 第二个能bar的值为1 fooo undefined
let [foo] = [];
let [bar,fooo] = [1];
// 可以有多维数组赋值
let [a,[b],c] = [1,[2,3],4]; console.log(a+"--"+b+"---"+b);
// set结构的赋值
let [d,e,f] = new Set(["d",'e','f']);console.log(d+"--"+e+"---"+f);
// 在进行赋值的时候可以使用默认值
let [d1,e1,f1 = '默认值'] = new Set(["d",'e',]);console.log(d1+"--"+e1+"---"+f1);
//如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。
let [a1 = af()] = [0]; console.log(a1);
function af(){
console.log('运行');
return 2;
}
// 对象的赋值 变量名需要和对象的属性值相同
let obj= {a2:"this foo",a3:"this bar"}
let {a2,a3} = obj;
console.log(a2+"----------"+a3);
// 如果变量名与属性名不一致, 需按照下面的写法 意思为前面为属性值 后面为变量值
let obj1= {a4:"this foo",a5:"this bar"}
let {a4:f4,a5:f5} = obj1;
console.log(f4+"----------"+f5);
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
//,分别是对loc、start、line三个属性的解构赋值
let { loc, loc: { start }, loc: { start: { line }} } = node;
//{x} = {x: 1}; 不能将大括号写在行首 会解释成代码块 有编译错误
//正确写法 ({x} = {x: 1});
// 获取对象属性 可以得到对应的属性值
let {scrollX,scrollY} = window;
// 字符串的解析
let [a6,a7,a8,a9,a10] = 'hello';
console.log(a6+"----------"+a7+"------"+a8+"------"+a9+'--------'+a10);
//解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s1} = true;
s1 === Boolean.prototype.toString // true
let arr = [1,2,3]
let {0:first,[arr.length-1]:last} = arr;
console.log(first); // 1
console.log(last); // 3
// {0:first,[arr.length-1]:last}中的0表示arr[0] [arr.length-1] = arr[[arr.length-1]] 并赋值给后面的变量名
// 解析重构的用途
//1. 叫还变量的值
let b2 = 1,b3 = 2;
[b2,b3] = [b3,b2];
//函数中返回对个值
(b4=()=>{
return [5,6];
})
console.log(b4());
//3.解构赋值可以方便地将一组参数与变量名对应起来。
function f({x, y, z}) { }
f({z: 3, y: 2, x: 1});
//4.提取json数据
//5. 可以设置函数的默认值
//任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就非常方便。
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
//加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。
//const { SourceMapConsumer, SourceNode } = require("source-map");