首页 > 解决方案 > 如何在 JavaScript ES6 中使用数组解构并分配给对象属性

问题描述

这段代码:

const eat = { when: 'now' }
const fruits = ['apple', 'orange']

eat.fruit = fruits[1] // orange

我可以像这样使用数组解构:

const [, selectedFruit] = fruits

eat.fruit = selectedFruit

但是我可以用它做一个单行吗?

标签: javascriptarraysecmascript-6destructuring

解决方案


你能用那个吗

[, eat.fruit] = fruits // remove const
console.log(eat)

推荐阅读