ES6 新的概念 解构赋值,这使得传值变得更为方便,可以想像是分解一个物品再分别套入对应的组件中,这样的作法让 JavaScript 的扩展上变得更为弹性,甚至直接取值不用再做多余的转换,提高程式码更佳的可读性。
概念与用途
主要是从物件、阵列中(object、array) 提取资料数值,再指定传入相对应的变数中原始上通常只能透过迴圈迭代的方式传值,现在 Destructuring 能让程式撰写上更为简短便利了// 阵列的解构赋值let [a, b] = [1, 2];console.log(a); // 1console.log(b); // 2// 物件的解构赋值const { attr1: x, attr2: y } = { attr1: 10, attr2: 20 };console.log(x); // 10console.log(y); // 20// 物件的属性也能解构赋值const { admin, user } = { admin: 'a', user: 'b' };console.log(admin); // 'a'console.log(user); // 'b'
其他资料类型的解构赋值
字串具有迭代器 Iterator 性质的资料类型常见的有 Set、Map (这 2 个都是 ES6 中的新产物)其实上面的字串也有 Iterator 性质// 字串的解构赋值let [x, y] = 'Hi';console.log(x, y); // 'H', 'i'// Set 资料结构let [x, y, z] = new Set([10, 20, 30]);console.log(x, y, z); // 10, 20, 30
Set: ES6 中新的资料类型,类似于阵列,但内容成员不会有重複的值
特性
基本使用
可以先宣告变数再解构赋值如果解构失败或变数没有对应值,变数的内容就会变成undefined
可以留空来略过某些值在解构时允许给定预设值// 先宣告变数再解构赋值let x, y;[x, y] = [5, 10];// 没有对应值的情况let [a, b, c] = [1, 2];console.log(c); // undefined// 留空来跳过第二个值function foo() { return [10, 20, 30];}let [a, , b] = foo();console.log(a, b); // 10, 30// 允许给定预设值let [x = 'a', y = 'b'] = ['A'];let {size = 'big', name = ''} = {name: 'A'}; console.log(x, y); // 'A', 'b'console.log(size, name); // 'big', 'A'
进阶使用
交换变数的值与 rest 参数做结合物件的先宣告后解构,需要在外层加上括号()
,这与阵列稍微不同// 交换变数的值 let a = 1, b = 10;[a, b] = [b, a];console.log(a); // 10console.log(b); // 1// 与 rest 参数做结合let [first, ...other] = [1, 2, 3, 4];console.log(first); // 1console.log(other); // [2, 3, 4]// 物件的先宣告后解构, 需加上括号()let x, y;({x, y} = {x: 1, y: 2});
可以使用在函数中的参数与回传值上主要是把阵列、物件套用上去,直接取变数的值内部给定预设值也是行的rest 参数:
...变数名称
一样是 ES6 中的新产物,把剩下的值或参数合在一起转成阵列
// 使用阵列在函数的参数上function add([x, y]) { return x + y;}add([1, 2]); // 3// 使用物件在函数的参数上function who({id, name = ''}) { console.log('No.' + id + ' is ' + name);}const user = { id: 10, name: 'ES6' };who(user); // 'No.10 is ES6'// 使用在函数的回传值上function getPoint(){ let x = 5, y = 10; return [x, y];}const point = {};[point.x, point.y] = getPoint();console.log(point); // {x: 5, y: 10}