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)];
To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Setting Properties of Existing Objects After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
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?.
If you have an existing array, you can use map.
var path = [0,1,2].map( x => new Cell(0, x))
or to mutate
path = path.map( x => {
x.value = x.yCoordinate - 1
return x
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With