如何从数组中解析键(ES6)

agm*_*984 4 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)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

有任何疑虑或违规吗?

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

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

{
  0: 'one',
  1: 'two',
  2: 'three'
}
Run Code Online (Sandbox Code Playgroud)

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

但是,它有效.

Nin*_*olz 6

您可以使用数组进行解构分配.那里你不需要索引,因为数组给出了顺序.

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)
Run Code Online (Sandbox Code Playgroud)