JavaScript中的解构及数组对象操作
JS的结构很灵活,参考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax
- 搜集多个参数使用
【...变量名】
表示 - 结构参数使用
【...需要解构的变量名】
表示
解构
列表解构
var parts = ['shoulder','knees'];
var lyrics = ['head',...parts,'and','toes'];//使用...结构
console.log(lyrics) // [ 'head', 'shoulder', 'knees', 'and', 'toes' ]
参数解构
function f(x,y,z){
console.log(x+y+z);
}
var args = [2,3,4];
f(...args);//9
数组解构
- 解构的时候,变量从左到右和元素对齐,可变参数放到最右边。
- 能对应到数据就返回数据,对应不到数据的返回默认值,如果没有默认值返回undefined。
const arr = [100,200,300];
let [x,y,z] = arr;
console.log('1----',x,y,z);
//丢弃
const [,b,] = arr;
console.log('2----',b);
// b=5 //异常,b声明未const
//少于数组元素
const [d,e] = arr;
console.log('3---',d,e);
//多余数组元素
const [m,n,o,p] = arr;
console.log('4----',m,n,o,p);
//可变变量
const [f,...