一. 概念:解析某一数据的结构,将我们想要的东西提取出来,赋值给变量或者常量
1 const [a, b, c] = [1, 2, 3]; 2 console.log(a, b, c);//1 2 3
二. 数组的解构赋值-解构匹配,索引值相同完成赋值
1.多维数组的解构
1 const [a, , c] = [1, [2, 3, 4], 5]; 2 console.log(a, c);//1 5 不取的可以先空着
//-----------------------------------------
3 const [a, b, c] = [1, [2, 3, 4], 5]; 4 console.log(a, b, c);//1 [2,3,4] 5
//--------------------------------------
5 const [a, [, , b], c] = [1, [2, 3, 4], 5]; 6 console.log(a, b, c);//1 4 5
//---------------------------------------
7 const [, a] = [1, [2, 3, 4], 5]; 8 console.log(a);//[2, 3, 4]
2.默认值
1 //生效条件 当数组成员===undefined,它的默认值才会生效 2 const [a, b] = []; 3 // 相当于const [a, b] = [undefined, undefined]; 4 console.log(a, b);//undefined undefined
//--------------------------------------------------------------
5 const [a = 1, b = 2] = [];//a = 1, b = 2 这就是设置默认值 6 // 相当于const [a, b] = [undefined, undefined]; 7 console.log(a, b);//1 2
//-------------------------------------------------------------
8 //默认值是表达式,惰性求值 9 function fn() { 10 console.log(1); 11 return 1; 12 } 13 const [a = 1, b = fn()] = [1, 2];//因为默认值没生效,fn()这句代码不会执行 14 15 console.log(a, b);//1 2
3.应用
①类数组的解构赋值
1 function fn() { 2 console.log(arguments);//[1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ] 3 const [a, b, c] = arguments; 4 console.log(a, b, c);//1 2 undefined 5 } 6 fn(1, 2);
1 <p>1</p> 2 <p>2</p> 3 <p>3</p> 4 <script> 5 var ps = document.querySelectorAll('p'); 6 console.log(ps); 7 const [a, b, c] = ps; 8 console.log(a, b, c); 9 <script>
②函数参数的解构赋值
1 const fn = ([a = 1, b = 2]) => {//这里的形参小括号不能省,因为参数的解构赋值相当于[a=1,b=2]=[3,4]是表达式不是单个参数 2 console.log(a, b);//3,4 3 } 4 fn([3, 4]); //传参过程就相当于形参=实参,相当于[a=1,b=2]=[3,4],可以解构赋值
③交换变量的值
1 let a = 1; 2 let b = 2; 3 //赋值等号右边是会求值然后赋值给左边的变量或者常量 4 [a, b] = [b, a]//这里a,b已经声明了,不能重复声明a,b了,也就是不能再let[x,y]=[y,x]了;
标签:ES6,const,log,undefined,解构,console,赋值 From: https://www.cnblogs.com/zhoushangquan/p/17036239.html