水牛的es6日记第五天【结构赋值】

20 篇文章 0 订阅
6 篇文章 0 订阅

解构赋值语法是一种JavaScript表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。

不带参数

let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

好吧,可能还是不够形象

这是原来代码

const user = { name: 'John Doe', age: 34 };

const name = user.name; // name = 'John Doe'
const age = user.age; // age = 34

然后结构赋值后

const { name, age } = user;
// name = 'John Doe', age = 34

按照惯例,来个练习

const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

// Only change code below this line

const today = HIGH_TEMPERATURES.today;
const tomorrow = HIGH_TEMPERATURES.tomorrow;

// Only change code above this line

答案是

const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

// Only change code below this line

const {today,tomorrow}=HIGH_TEMPERATURES;

// Only change code above this line

带入参数

使用上一个示例中的相同对象:

const user = { name: 'John Doe', age: 34 };

在分配中给新变量名称的方法如下:

const { name: userName, age: userAge } = user;
// userName = 'John Doe', userAge = 34

小测

const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

// Only change code below this line
  
const highToday = HIGH_TEMPERATURES.today;
const highTomorrow = HIGH_TEMPERATURES.tomorrow; 

// Only change code above this line

将两个分配替换为等效的解构分配。它仍应从HIGH_TEMPERATURES对象分配变量highToday和highTomorrow today和tomorrow的值。

答案

const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

// Only change code below this line
  
const {today:highToday,tomorrow:highTomorrow}=HIGH_TEMPERATURES;

// Only change code above this line

如果是被{}包裹的,用这种写法

const LOCAL_FORECAST = {
  yesterday: { low: 61, high: 75 },
  today: { low: 64, high: 77 },
  tomorrow: { low: 68, high: 80 }
};

// Only change code below this line
  
const{today:{low:lowToday,high:highToday}}=LOCAL_FORECAST;

// Only change code above this line

要调换a ,b两个

let a = 8, b = 6;
// Only change code below this line
[a,b]=[b,a];

res参数和destructuring参数混合搭配起来的用法

const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  "use strict";
  // Only change code below this line
  const [a,b,...arr] = list; // Change this line
  // Only change code above this line
  return arr;
}
const arr = removeFirstTwo(source);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值