0

I have some snippet of code

 for(var i=0; i < this.arr2.length; i++) {
      arr.push({
          id: i.toString(),
          label: this.arr2[i],
          display: () => this.arr2[i]
      })
  }

Why is the display undefined if i am doing something like this

let val = this.arr2[i];
display: () => val 

is working fine

marvel308
  • 10,288
  • 1
  • 21
  • 32
Walter White
  • 976
  • 4
  • 12
  • 29

1 Answers1

1

You should use let keyword in order to declare a block scope local variable

for(let = 0; i < this.arr2.length; i++) {
  arr.push({
      id: i.toString(),
      label: this.arr2[i],
      display: () => this.arr2[i]
  })
}

For this example it is easily to use map method.

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};
});

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());
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128