解构是ES6新加的解构功能,可以使得我们获取数据更方便,从而提高日常编码效率。
1.数组解构
const numbers = ['one','two','three','four']
// 获取前两个值
const [one, two] = numbers;
console.log(one,two) // one two
// 获取第一个和第三个值
const [one, , three] = numbers;
console.log(one, three) //three
// 获取第一个和后边所有的值,...others参数只能存在于最后
const [one, ...others] = numbers;
console.log(one, others) // 获取第一个值,和后边所有值组成的一个数组
2.数组解构设置默认值
const details = ['JellyBool', 'laravist.com'];
const [name, website, category = 'PHP'] = details;
console.log(name, website, category)// JellyBool laravist.com PHP
数组解构也可以有默认值,只有当相对应的元素明确的为undefined时,才会使用默认值
数组解构例子
//交换a与b的值
let a=10;
let b=20;
//传统方法
var term;
term =a;
a = b;
b = term;
console.log(a,b) // 20 10
// 数组解构
[a,b]= [b,a]
console.log(b) // a 20
console.log(b) // b 10