1. 交换变量的值.
[x ,y] = [y, x];
2. 从函数返回多个值.
//数组
function example(){
return [1, 2 , 3]
}
var [a, b, c] = example();
//对象
function example(){
return {
foo: 1,
bar: 2
}
}
var {foo, bar } = example();
3. 函数参数的定义.
//有序值
function f([x, y, z]){ ... }
f([1,2,3])
//无序值
function f({x, y, z}){ ... }
f(y: 1, z: 2, x: 3)
4. 提取json数据.
var jsonData = {
id: 42,
status: 'ok',
data: [867, 5309]
}
let {id, status, data:arr} = jsonData;
console.log(id, status, arr) // 42, "ok", [867, 5309]
5. 函数的默认值.
function a(x=1, y=2){
return x + y ;
};
a() / / 3
6. 遍历Map解构.
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for(let [key, value] of map){
console.log(key+ 'is' + value)
}
// first is hello
// second is world
网友评论