我有一些代码片段
for(var i=0; i < this.arr2.length; i++) {
arr.push({
id: i.toString(),
label: this.arr2[i],
display: () => this.arr2[i]
})
}
如果我正在做这样的事情,为什么显示未定义
let val = this.arr2[i];
display: () => val
工作正常
最佳答案
您应该使用let
关键字来声明 block scope
本地变量
for(let = 0; i < this.arr2.length; i++) {
arr.push({
id: i.toString(),
label: this.arr2[i],
display: () => this.arr2[i]
})
}
对于此示例,可以轻松使用 map
方法。
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
arr=arr2.map(function(item,i){
return {id:i,label:item,display:()=>item};
});
简短示例:
arr2=[1,2,3,4,5];
arr=arr2.map(function(item,i){
return {id:i,label:item,display:()=>item};
});
console.log(arr[1].display());
关于javascript - 函数不从数组返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45751477/