0

I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.

When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.

var array = []; 
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}

However, when I call the value held in that property (i.e.):

console.log(array[2].someFunction)

It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.

cfnerd
  • 3,658
  • 12
  • 32
  • 44
  • You need to call `someFunction`. And use `let` instead of `var i`. Your current loop crashes because it is trying to set `someFunction()` of `undefined` – Nick Parsons Dec 14 '19 at 03:08
  • 1
    Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Nick Parsons Dec 14 '19 at 03:09

2 Answers2

0

It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:

var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
    array[i].index = i;
    array[i].someFunction = function(){console.log(this.index);}
}

//and see that it's working...
for(var i = 0; i < array.length; i++){
    array[i].someFunction();
}
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
0

Basically you had some problems in your code, like:

  • not defining number
  • using var instead of let
  • not defining the object
  • using the same value as parameter of the function

here you have the working solution.

var array = [];
// numbers was not defined.
const number = 10;

// use let instead of var
for (let i = 0; i < number; i++) {
  // you are not instantiating your object, here is an example.
  array[i] = {
    "foo": "bar",
    "index": i,
  }
  // you have to change i to j, because if you use i
  // it will be the parameter of the function
  array[i].someFunction = function(j) {
    console.log('index: ', i);
    console.log('parameter: ', j)
  }
}
// we see the function
console.log(array[2].someFunction)

// we call the function succesfully
array[2].someFunction(100);
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19