首页 > 解决方案 > 从数组中给出对象值的每个属性

问题描述

我有一个对象和数组,数组中的每个元素都对应于对象属性。

它看起来像这样:

let keys = {
  kShift: null,
  kSpace: null,
  kEnter: null,
  kA: null,
  kS: null,
  kD: null,
  kW: null
}

let array = document.querySelectorAll('.k')
<div class="k">shift</div>
<div class="k">space</div>
<div class="k">enter</div>
<div class="k">a</div>
<div class="k">s</div>
<div class="k">d</div>
<div class="k">w</div>

我需要对象的每个属性来从数组中获取相应的值。

它看起来是这样的:

  keys.kShift = array[0] // first property of object is the first element in array
  keys.kSpace = array[1] // second property of object is the second element in array
  keys.kEnter = array[2] // third property of object is the third element in array

等等

所以我需要找到最好的方法来做到这一点

标签: javascriptarraysalgorithmobjectproperties

解决方案


使用 ES6 解构数组。必须确保右侧的数组项与声明的变量的顺序相同。

const [ kShift, kSpace, kEnter, kA, kS, kD, kW ] = document.querySelectorAll('.k')
const keys = { kShift, kSpace, kEnter, kA, kS, kD, kW }

推荐阅读