javascript - Function don't return value from array -
this question has answer here:
i have snippet of code
for(var i=0; < this.arr2.length; i++) { arr.push({ id: i.tostring(), label: this.arr2[i], display: () => this.arr2[i] }) }
why display undefined if doing
let val = this.arr2[i]; display: () => val
is working fine
you should use let
keyword in order declare block scope
local variable
for(let = 0; < this.arr2.length; i++) { arr.push({ id: i.tostring(), label: this.arr2[i], display: () => this.arr2[i] }) }
for example use map
method.
the map() method creates new array results of calling provided function on every element in calling array.
arr=arr2.map(function(item,i){ return {id:i,label:item,display:()=>item}; });
short example:
arr2=[1,2,3,4,5]; arr=arr2.map(function(item,i){ return {id:i,label:item,display:()=>item}; }); console.log(arr[1].display());
Comments
Post a Comment