Javascript 解构赋值,将属性/值从对象/数组中取出,赋值给其他变量

概念:解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。
var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

({ a, b } = { a: 1, b: 2 });
console.log(a); // 1
console.log(b); // 2


({a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4});
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}




应用:使用解构赋值交换两个变量的值。
var a = 3;
var b = 8;

[a, b] = [b, a];
console.log(a); // 8
console.log(b); // 3


应用:解析一个从函数返回的数组
function fn() {
  return [6, 8];
}

var a, b; 
[a, b] = fn(); 
console.log(a); // 6
console.log(b); // 8

应用:忽略不感兴趣的值
function f() {
  return [6, 7, 8];
}

var [a, , b] = f();
console.log(a); // 6
console.log(b); // 8

应用:将剩余数组赋值给一个变量
var [a, ...b] = [6, 7, 8];
console.log(a); // 6
console.log(b); // [7, 8]


应用:对象结构赋值
var people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (var {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值