本文实例讲述了ES6新特性之变量的解构赋值。分享给大家供大家参考,具体如下:
1. 数组的解构赋值
提取值,按照对应位置,对变量赋值
var [a,b] = [1,2]; //a = 1;b = 2
//② 下面是一些使用嵌套数组进行解构
var [d,[[c],f]] = [1,[[2],3]];
var [,third] = ["foo","bar","baz"];//third = "baz"
var [head,...tail] = [1,2,3,4];//head = 1;tail = [2,4]
//③不完全结构
var [x,y] = [1,6]; //x = 1;y = 2
//④ 解构赋值允许指定默认值
var [foo = true] = []; //foo = true
var [x,y='b'] = ['a'] // x='a',y='b'
var [x,y='b'] = ['a',undefined] // x='a',y='b'
//⑤ 解构不成功,变量的值就等于undefined
var [a6,a7] = [1]; //a7 = undefined
2. 对Set 的解构赋值
3. 对象的解构赋值
属性没有次序,变量必须与属性同名,才能取到正确的值
var { x,y } = { x: "aaa",y: "bbb" };//x = aaa,y = bbbb
var { c } = { a: "aaa",b: "bbb" }; // c = undefined
//严格遵守变量名与属性同名
var { d: e } = { d: "aaa",f: "bbb" }; //e = aaa
//指定默认值
var {x,y = 5} = {x: 1};// x = 1,y = 5
4. 用于遍历 Map
获取键值对
for (let [key,value] of map) {
console.log(key + " is " + value);
}
// 获取键名
for (let [key] of map) {
console.log(key);
}
// 获取值
for (let [,value] of map) {
console.log(value);
}
希望本文所述对大家ECMAScript程序设计有所帮助。