问题
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)];
回答1:
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?.
回答2:
A simple for loop should work:
var path = [],
len = 10;
for (
var idx = 0;
idx < len;
path.push(new Cell(0,++idx))
)
回答3:
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
})
回答4:
<html>
<body>
<p id="demo"></p>
<script>
function Cell(x,y){
this.xCoordinate = x;
this.yCoordinate = y;
this.value;
}
function setValues(element, index, array){
array[index].value = index+1;
}
var path = [new Cell(0,0), new Cell(0,1), new Cell(0,2)];
path.forEach(setValues);
document.getElementById("demo").innerHTML = path[2].value;
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/35879307/change-properties-of-every-item-in-an-array