【问题标题】:How to use array destructuring and assign to an object property in JavaScript ES6如何在 JavaScript ES6 中使用数组解构并分配给对象属性
【发布时间】:2020-06-11 18:33:57
【问题描述】:

这段代码:

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

eat.fruit = fruits[1] // orange

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

const [, selectedFruit] = fruits

eat.fruit = selectedFruit

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

【问题讨论】:

    标签: javascript arrays ecmascript-6 destructuring


    【解决方案1】:

    你可以在这里使用合并:

    let eat = { when: 'now' }
    const fruits = ['apple', 'orange']
    
    eat = {...eat, fruit: fruits[1]}
    console.log( eat )

    【讨论】:

    • 虽然有效,但我不会推荐这个。仅仅为了获得一个班轮解决方案而牺牲效率并不是一个好主意,至少恕我直言。相反,可以创建一个新属性并通过在同一语句中查找来为其分配选定的值,例如 eat.fruit = fruits.indexOf() 或类似的东西。
    【解决方案2】:

    你能用那个吗

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-06
      • 2019-05-22
      • 1970-01-01
      • 2019-12-30
      • 2018-04-12
      • 2018-04-25
      • 1970-01-01
      • 2014-01-16
      相关资源
      最近更新 更多