javascript - 如何从数组中解构键(ES6)

标签 javascript ecmascript-6

我们只是根据直觉编写了这段代码,而且它起作用了。我很确定这是可以接受的。我只想确定:

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const {
  0: newState,
  1: newActions,
  2: newChange,
} = [state, actions, change]

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)

有更好的方法吗?

有任何疑虑或违规行为吗?

我找不到这方面的任何例子,只是试了一下,因为我记得:

['one', 'two', 'three'] 可以表示为一个对象:

{
  0: 'one',
  1: 'two',
  2: 'three'
}

这里没有完全列出: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

但是,它有效。

最佳答案

您可以为 destructuring assignment 使用数组.那里不需要索引,因为数组给出了顺序。

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const [newState, newActions, newChange] = [state, actions, change];

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)

关于javascript - 如何从数组中解构键(ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47408730/

相关文章:

asp.net - 调试 ASP.Net 网站和 window.onerror

javascript变量在函数内丢失

javascript - Webpack 类没有从构造函数到类的方法共享 this

javascript - 如何使用基于其他数组的特定动态键来过滤/减少对象数组

angular - 模板文字中的 Atom HTML 语法突出显示(对于 angular2)

javascript - React ES6 SystemJS - 未捕获( promise )错误 : Unexpected token <(…)

javascript - Node.js - 语法错误 : Unexpected token import

javascript - 交换情况 JavaScript

javascript - 通过重新定义使一个函数运行一次

javascript - 使用 react-router 滚动到同一页面上的组件