相信你們對解構賦值並不陌生:
阮大佬ECMAScript 6 入門
裏面有講七種用途,用得最多莫過於json數據處理html
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
固然變換變量的值,也是用得較多的。es6
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
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被分配一個對象,該對象具備在模式中未說起其鍵的全部數據屬性。json
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);