更改数组中每个项目的属性? [英] Change properties of every item in an array?
问题描述
我需要设置该数组中每个项目的值,向上计数.
I need to set the value of every item in this array, counting up.
例如,path [0] .value = 1,path [1] .value = 2等等...
So, for example, path[0].value = 1, path[1].value = 2 etc...
我正在寻找最有效的方法.
I'm looking for the most efficient way to do this.
我认为for循环是最好的方法,但是我想学习其他方法.可以使用map()方法或forEach()完成吗?声明中的...呢?我想用纯JS做到这一点,但是如果您可以用jQuery教我一种更好的方法,我也很想学习.
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.
先谢谢了.
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)];
推荐答案
您可以使用for
循环或forEach
:
for(var i=0; i<path.length; ++i)
path[i].value = i+1;
path.forEach(function(cell, i) {
cell.value = i + 1;
});
由于为什么在数组迭代中使用"for…in"这样的好主意,所以最好避免使用for...in
?
这篇关于更改数组中每个项目的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!