const arr = [1, 2, 3];
const a = arr[0];
const b = arr[1];
const c = arr[2];
console.log(a, b, c); //1 2 3
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
解析某一数据的结构,将我们想要的东西提取出来,赋值给变量或常量
[]=[1,2,3];
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
const [a, [ , ,b], c] = [1, [2,4,5], 3];
console.log(a, b, c,); //1 5 3
function func(){
const [a,b] = arguments;
console.log(a,b) // 1.2
}
func(1,2);
<p>123</p>
<p>321</p>
<p>456</p>
const [p1,p2,p3] = document.querySelectorAll(‘p‘);
console.log(p1,p2,p3) //<p>123</p> <p>321</p><p>456</p>
const array =[1,1];
const add = arr=> arr[0] + arr[1];
console.log(add(array)); //2
//使用解构赋值接收参数
const add = ([x,y])=> x + y;
console.log(add(array)); //2
//数组形式的解构赋值
const [a,b] = ‘hello‘;
console.log(a,b); // h e
//对象形式的解构赋值 通过索引值来获取
const{0:a} = ‘hello‘;
console.log(a); //h
字符串既可以按照数组形式来解构赋值,也可以按对象形式来解构赋值
先将等号右边的值转为对象
console.log(new Number(123));cosnt{a } = 123;console.log(a); // undefined
由于undefined和null无法转为对象,所以对他们进行解构赋值,都会报错
原文:https://www.cnblogs.com/LiHaoGo/p/14838977.html