代码之家  ›  专栏  ›  技术社区  ›  agm1984

如何从阵列中分解密钥(ES6)

  •  4
  • agm1984  · 技术社区  · 7 年前

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

    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

    但是,它是有效的。

    2 回复  |  直到 7 年前
        1
  •  6
  •   Nina Scholz    7 年前

    可以将数组用于 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)
        2
  •  2
  •   Ori Drori    7 年前

    使用 array destructuring :

    const state = { inProgress: true }
    const actions = 'COMPLETE_RICE'
    const change = { inProgress: false, rice: 'cooked' }
    
    const [newState, newActions, newChange] = [state, actions, change]
    
    console.log('New State:', newState)
    console.log('New Actions:', newActions)
    console.log('New Change:', newChange)