javascript - 从数组中给出对象值的每个属性
问题描述
我有一个对象和数组,数组中的每个元素都对应于对象属性。
它看起来像这样:
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
等等
所以我需要找到最好的方法来做到这一点
解决方案
使用 ES6 解构数组。必须确保右侧的数组项与声明的变量的顺序相同。
const [ kShift, kSpace, kEnter, kA, kS, kD, kW ] = document.querySelectorAll('.k')
const keys = { kShift, kSpace, kEnter, kA, kS, kD, kW }
推荐阅读
- javascript - Ajax 成功后运行 JavaScript 函数
- python - 对项目进行排序但防止相同名称的项目彼此相邻;还在集合中添加随机化
- java - 使用我访问过的节点查找到原点的最短路径的图表
- ignite - 删除 Ignite 表不会从持久层删除数据
- git - Git - 如果我从父分支中删除提交,它是否也会从提交在父分支上时创建的子分支中消失?
- html - Angular ::ng-deep {} 在 *.component.css ng5-slider 中不起作用
- asp.net-core - 在代码部分的组件中使用 foreach 循环中的当前项
- tensorflow - Tensorflow Keras 在训练和验证中的类别数量不同
- reactjs - 如何在子反应组件中拥有反应路由器链接
- javascript - 无法将字段添加到参数对象