ES6 - 数组 && 对象 操作总结
解构赋值
按照一定模式,可以从数组和对象中提取值,从而对变量进行赋值操作。
主要在数组和对象中执行解构赋值操作,下面罗列常用的情景操作。
数组的解构赋值
基本使用:
1 var [a,b,c]=[1,2,3]; 2 console.log(a) //1 3 console.log(b) //2 4 console.log(c) //3
如果解构不成功,左侧变量的值就会为undefined
1 var [a,b,c]=[1,3]; 2 console.log(a) //1 3 console.log(b) //3 4 console.log(c) //undefined
嵌套:
1 var [a,[[b],c]]=[1,[[2],3]]; 2 console.log(a) //1 3 console.log(b)//2 4 console.log(c) //3
可忽略:
1 var [a,,c]=[1,2,3]; 2 console.log(a) //1 3 console.log(c) //3
剩余运算符:
1 var [a,...b]=[1,2,3,4,5]; 2 console.log(a) //1 3 console.log(b) //2,3,4,5
1 var [a,...b]=['A']; 2 console.log(a) //A 3 console.log(b) //[]
字符串:
1 var [a, b, c, d, e] = 'hello' 2 console.log(a) //h 3 console.log(b) //e 4 console.log(c) //l 5 console.log(d) //l 6 console.log(e) //o
默认值:
1 var [a = 1,b]=[2]; 2 console.log(a) //2 3 console.log(b) //undefined
1 var [a = 1,b = 2]=[undefined,4]; 2 console.log(a) //1 3 console.log(b) //4
对象的解构赋值
基本使用:
变量
必须与属性
同名
,才能取到正确的值,位置顺序没关系。
var { name, age } = { name: "sss", bar: "12" }; console.log(name) //sss console.log(age) //undefined
嵌套:
1 var obj = {p:['tom',{age:'12'}]}; 2 var {p:[QName,{age}]} = obj; 3 console.log(QName) //tom 4 console.log(age) //12
忽略:
1 var obj = {p:['tom',{age:'12'}]}; 2 var {p:[,{age}]} = obj; 3 console.log(age) //12
剩余运算符:
1 var {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}; 2 console.log(a) //10 3 console.log(b) //20 4 console.log(rest) //{c:30 ,d:40}