相信大家对解构赋值并不陌生:
阮大佬 ECMAScript 6 入门
里面有讲七种用途,用得最多莫过于 json 数据处理
json 数据处理
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let {id, status, data: number} = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
当然变换变量的值,也是用得较多的。
交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
let x3 = "a";
let y3 = "b";
let z3 = "c";
[x3,y3,z3] = [z3,y3,x3];
console.log(x3,y3,z3);//c,b,a
for..of 中使用
const arrC = ["a", "b"];
for(const [index, element] of arrC.entries()){console.log(index,element);
}
//0 "a"
//1 "b"
还可以对象解构原始值(字符长度等。。)
const {length: len} = "abc";
console.log(len);//3
对象的剩余属性构造
const objA = {a: 1, b: 2, c: 3};
const {a:propValue, ...remaining}= objA;
console.log(propValue,remaining);//1 {b: 2, c: 3}
remaining 被分配一个对象,该对象具有在模式中未提及其键的所有数据属性。
数组的剩余属性构造
const [xx,yy,...rest] = ["a","b","c","d"];
console.log(xx,yy,rest);//a b ["c","d"]
rest 被分配一个对象,该数组具有在模式中未提及的所有元素。
数组解构:返回数组的操作
const [,year,month,day] = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec('2999-12-31')
console.log(/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec('2999-12-31'));//["2999-12-31", "2999", "12", "31", index: 0, input: "2999-12-31", groups: undefined]
console.log(year,month,day);//2999 12 31
处理函数返回结果
function findElement(arr, predicate) {for (let index=0; index < arr.length; index++) {const value = arr[index];
if (predicate(value)) {return { value, index};
}
}
return {value: undefined, index: -1};
}
const arrD = [7, 8, 6];
// const {value, index} = findElement(arrD, x => x % 2 === 0);// 可以一起输出,也可以单个解构输出
const {value} = findElement(arrD, x => x % 2 === 0);
const {index} = findElement(arrD, x => x % 2 === 0);
console.log(value,index);
参考文献:JavaScript for impatient programmers