大家好,我正在尝试将数组的每个元素作为某些对象的属性值。因此,我使用了一个函数,但它根本不是动态的,因为我需要在调用函数后始终指定数组的索引。
这是我的代码:
function grab(){
var arr= [123456,987654]
return arr
}
var arrayObjects= [
{title: "miami", hash: grab()[0]},
{title: "new york", hash: grab()[1]}
]
console.log(arrayObjects[0].hash)
另一种更有效的方法是什么?
最佳答案
尝试这样。直接在函数中传递值
function grab(n) {
return [123456, 987654][n];
}
var arrayObjects = [{ title: "miami" }, { title: "new york"}]
arrayObjects.forEach((a,b)=> a['hash'] = grab(b));
console.log(arrayObjects[0].hash)
关于javascript - 使用函数获取数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978264/