1.object.assign()
a = [1,2,3]
b = object.assign([],a)
b.push(8)
// a => [1,2,3] b => [1,2,3,8]
// 在上面的代码中,修改数组b将不会影响数组a。因为使用Object.assign()创建了一个新的副本,由数组b指向。同样也可以使用操作符(...)执行不可变操作
a = [1,2,3]
b = [...a,4,5,6]
// a => [1,2,3] b => [1,2,3,4,5,6]
2.解构赋值
var [a,b,...rest] = [10,20,30,40,50];
// a => 10 b => 20 rest => [30,40,50]
({a, b} = {a:10, b:20})
//a => 10 b => 20
({a, b, ...rest} = {a:10, b:20, c:30, d:40})
//a => 10, b => 20, rest => {c:30, d:40}
1 变量声明并赋值
const foo = ['one', 'two', 'three'];
const [one , two, three] = foo;
// one => 'one' two => 'two' three => 'three'
2.默认值 (防止后台给一个undefined)
const [a=5, b=7] = [1]
// a => 1 b => 7
3.交换变量
const a = 1;
const b = 2;
[a, b] = [b, a];
// a => 2 b => 1
4.函数返回的数组
function f(){
return [1, 2];
}
const a, b;
[a, b] = f();
//a => 1. b => 2
5.取想要的值
const [a, , b] = [1, 2, 3]
//b => 3
来源于
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment