let [firstName, surName] = 'John Smith'.split(' ');
1
let [firstName, surName] = ['John', 'Smith'];
1 2 3
let arr = ['John', 'Smith']; let firstName = arr[0]; let surName = arr[1];
以上三种形式效果等价,前两种就是数组的解构赋值
忽略元素
可以在等号左边通过逗号来忽略元素
1 2
let [a,,c] = [1,2,3]; alert(c); //3
等号右侧适用于任何可迭代的数组
数组解构可以解构通用的数组,但并不局限,也可以解构任何可迭代的数组,例如字符串
1
let [a,b,c] = "123";
等号左侧适用于任何可赋值的元素
1 2
let user = {}; [user.firstName, user.surName] = 'John Smith'.split(' ');
获取数组剩下的元素
通常我们想要的数据远比对象/数组本身提供的少,我们可以通过...的方式来收集剩余的项
1 2 3 4 5
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; // rest 是包含从第三项开始的其余数组项的数组 alert(rest[0]); // Consul alert(rest[1]); // of the Roman Republic alert(rest.length); // 2