解构赋值 是一种特殊的语法,它使我们可以将数组或对象“拆包”为到一系列变量中
上述代码将一个数组解构到变量中,我们就可以针对这些变量进行操作,而不是针对原来的数组元素
解构另一个用法是结合split函数使用
let [firstName, secondName] = "Ilya Kantor".split(' ');解构不等于破坏
它是通过将结构中的各个元素复制到变量中,但是数组本身不会被修改
// let [firstName, secondName] = arr; let firstName = arr[0]; let secondName = arr[1];可以使用忽略逗号元素
数组中不需要的元素可以添加额外的逗号来跳过
let [firstName, , secondName] = ["one", "two", "three", "four"]; console.log( secondName ); // 3等号右侧可以是任何迭代对象
let [a, b, c] = "abc"; // ["a", "b", "c"]等号左侧赋值任何内容
let user = {}; [user.name, user.surname] = "Ilya Kantor".split(' '); console.log(user.name); // Ilya剩余元素…
如果我们想要将数组中后续元素全部收集起来,可以使用三个点...来收集后续元素
let [num1,num2,...rest] = [1,2,3,4,5,6,7,8,9] console.log(num1); // 1 console.log(num2); // 2 //rest也是数组类型 console.log(rest[0]); // 3 console.log(rest[1]); // 4 console.log(rest.length); // 7默认值
赋值语句中,如果变量多余数组中的元素,赋值不会报错,未被赋值的变量默认为undefined
let [firstName, surname] = []; console.log(firstName); // undefined console.log(surname); // undefined可以给未被赋值的变量添加一个默认值
let [firstName = "girl", surname = "boy"] = []; console.log(firstName); // girl console.log(surname); // boy在等号右侧是一个已经存在的对象,把它拆开放到变量中,左侧包含右侧对象相应属性的模式
let options = { name: "Menu", width: 100, height: 200 }; let {name, width, height} = options; console.log(name); // Menu console.log(width); // 100 console.log(height); // 200也可以把一个属性赋值给另一个名字的变量,用冒号来指定:
let options = { name: "Menu", width: 100, height: 200 }; let {width: w, height: h, name} = options; // width -> w // height -> h // name -> name console.log(name); // Menu console.log(w); // 100 console.log(h); // 200可以将冒号和等号结合起来
let options = { name: "Menu" }; let {width: w = 100, height: h = 200, name} = options; console.log(name); // Menu console.log(w); // 100 console.log(h); // 200也可以只提取我们所需要的内容
let options = { name: "Menu", width: 100, height: 200 }; let { name } = options; console.log(title); // Menu对象可以使用剩余模式…
let options = { name: "Menu", height: 200, width: 100 }; let {name, ...rest} = options; console.log(rest.height); // 200 console.log(rest.width); // 100如果一个对象或数组嵌套了其他的对象和数组,可以使用一个更复杂的模式来提取数据
let options = { size: { width: 100, height: 200 }, name: ["boy", "girl"], age: 18 }; let { size: { // 把 size 赋值到这里 width, height }, name: [name1, name2], // 把 items 赋值到这里 title = "Menu" // 对象中不存在使用默认值 } = options; console.log(title); // Menu console.log(width); // 100 console.log(height); // 200 console.log(name1); // boy console.log(name2); // girr