如何使用数组解构并在JavaScript ES6中分配给对象属性

问题描述 投票:0回答:2

此代码:

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

eat.fruit = fruits[1] // orange

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

const [, selectedFruit] = fruits

eat.fruit = selectedFruit

但是我可以用它做成单线吗?

javascript arrays ecmascript-6 destructuring
2个回答
1
投票

您可以在此处使用合并:

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

eat = {...eat, fruit: fruits[1]}
console.log( eat )

0
投票

您可以使用那个

[, eat.fruit] = fruits // remove const
console.log(eat)
© www.soinside.com 2019 - 2024. All rights reserved.