Search code examples
javascriptjqueryarraysforeachfor-in-loop

Change properties of every item in an array?


I need to set the value of every item in this array, counting up.

So, for example, path[0].value = 1, path[1].value = 2 etc...

EDIT: I'm looking for the most efficient way to do this.

I think a for loop is the best way, but I want to learn other ways. Can it be done with the map() method or forEach()? What about a for... in statement? I'd like to do it with pure JS, but if you can teach me a better way with jQuery, I'd be interested to learn that too.

Thanks in advance.

function Cell(x,y){
    this.xCoordinate = x;
    this.yCoordinate = y;
    this.value;
}
var path = [new Cell(0,0), new Cell(0,1), new Cell(0,2)];


Solution

  • You can use a for loop or forEach:

    for(var i=0; i<path.length; ++i)
      path[i].value = i+1;
    
    path.forEach(function(cell, i) {
      cell.value = i + 1;
    });
    

    Better avoid for...in because of Why is using “for…in” with array iteration such a bad idea?.