啥是解构赋值?
我们都知道,数组和对象是我们常用的数据结构,对象和数组把数据“整合”在其中,但是可能我的需求需要取出数据到单独的变量中,这时候解构赋值就起到了作用....
解构赋值 是一种特殊的语法,它使我们可以将数组或对象“拆包”为到一系列变量中,因为有时候使用变量更加方便。解构操作对那些具有很多参数和默认值等的函数也很奏效。
数组解构
直接康康代码
let names = ["tim","lucy","wang"];
let [firstName,secondName,lastName] = names;
console.log(firstName); //tim
console.log(secondName); //lucy
console.log(lastName); //wang
这种语法叫做“解构赋值”,因为它通过将结构中的各元素复制到变量中来达到“解构”的目的。但数组本身是没有被修改的。
这只是下面这些代码的更精简的写法而已:
// let [firstName,secondName,lastName] = names;
let firstName = names[0];
let secondName = names[1];
...
解构赋值中忽略数组中不想要的元素
// 不需要第二个元素
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
在上面的代码中,数组的第二个元素被跳过了,第三个元素被赋值给了 title 变量,数组中剩下的元素也都被跳过了(因为在这没有对应给它们的变量)。
对象解构
不多BB,直接上演示代码
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
或者是这样的
let {height,width,title} = {title:"Menu",height: 200,width: 100}
alert(title); // Menu
alert(width); // 100
alert(height); // 200
通过上述现象发现,对象的解构,和顺序无关,和与对象的属性名是否匹配相关,
我可以像下面的写法一样,不必让我的变量名一定是对象的属性名,也就是嗦,我指定解构对象的变量名。。。
let options = {
title: "Menu",
width: 100,
height: 200
};
let {width: w, height: h, title} = options;
alert(title); // Menu
alert(w); // 100
alert(h); // 200