ES6 变量解构赋值的用途

付费节点推荐


免费节点


节点使用教程


  • 数组
let [a, b, c] = [1, 2, 3];
let [foo = true] = [];
  • 对象
let { foo, bar } = { foo: "aaa", bar: "bbb" };
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
  • 字符串
const [a, b, c, d, e] = 'hello';
  • 函数
function add([x, y]){
 return x + y;
}
add([1, 2]); // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b);
function move({x = 0, y = 0} = {}) {
 return [x, y];
}
move({x: 3, y: 8}); // [3, 8]

解构赋值的用途

  • 交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
  • 从函数返回多个值
function example() {
 return [1, 2, 3];
}
let [a, b, c] = example();
function app() {
 return {
 foo: 1,
 bar: 2
 };
}
let { foo, bar } = app();
  • 函数参数的定义

function f([x, y, z]) { … }
f([1, 2, 3]);

function g({ x, y, z }) { … }
g({ z: 3, y: 2, x: 1 });

 

  • 提取json数据
let jsonData = {
 id: 42,
 status: 'OK',
 data: [867, 5309]
};
let { id, status, data: number } = jsonData;
  • 函数参数的默认值
jQuery.ajax = function(url, {
 async = true,
 beforeSend = function() {},
 cache = true,
 complete = function() {},
 crossDomain = false,
 global = true,
 // ... more config
}) {
 // ... do stuff
};
  • 遍历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);
}

  • 输入模块的指定方法
const { SourceConsumer, sourceNode } = require('source-map');

未经允许不得转载:Bcoder资源网 » ES6 变量解构赋值的用途

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册