更改数组中每个项目的属性?
Change properties of every item in an array?
我需要设置这个数组中每一项的值,向上计数。
因此,例如,路径[0].value = 1、路径[1].value = 2 等...
编辑:我正在寻找最有效的方法。
我认为for循环是最好的方法,但我想学习其他方法。能不能用map()方法或者forEach()方法来完成? for...in 语句呢?我想用纯 JS 来做,但如果你能教我一个更好的方法 jQuery,我也有兴趣学习。
提前致谢。
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)];
如果你有一个现有的数组,你可以使用映射。
var path = [0,1,2].map( x => new Cell(0, x))
或变异
path = path.map( x => {
x.value = x.yCoordinate - 1
return x
})
您可以使用 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
,因为 Why is using “for…in” with array iteration such a bad idea?。
一个简单的 for 循环应该可以工作:
var path = [],
len = 10;
for (
var idx = 0;
idx < len;
path.push(new Cell(0,++idx))
)
<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>
我需要设置这个数组中每一项的值,向上计数。
因此,例如,路径[0].value = 1、路径[1].value = 2 等...
编辑:我正在寻找最有效的方法。
我认为for循环是最好的方法,但我想学习其他方法。能不能用map()方法或者forEach()方法来完成? for...in 语句呢?我想用纯 JS 来做,但如果你能教我一个更好的方法 jQuery,我也有兴趣学习。
提前致谢。
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)];
如果你有一个现有的数组,你可以使用映射。
var path = [0,1,2].map( x => new Cell(0, x))
或变异
path = path.map( x => {
x.value = x.yCoordinate - 1
return x
})
您可以使用 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
,因为 Why is using “for…in” with array iteration such a bad idea?。
一个简单的 for 循环应该可以工作:
var path = [],
len = 10;
for (
var idx = 0;
idx < len;
path.push(new Cell(0,++idx))
)
<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>