ES6新特性四:变量的解构赋值实例
Dason_yu 人气:0本文实例讲述了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, 3, 4] //③不完全结构 var [x, y] = [1,2,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 的解构赋值
[a, b, c] = new Set(["a", "b", "c"]) console.log(a) // "a"
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
var map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); //获取键值对 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程序设计有所帮助。
加载全部内容