更改数组中每个项的属性

Change properties of every item in an array?

本文关键字:属性 数组      更新时间:2023-09-26

我需要设置这个数组中每个项目的值,向上计数。

因此,例如,路径[0].值= 1,路径[1].值= 2等...

编辑:我正在寻找最有效的方法来做到这一点。

我认为 for 循环是最好的方法,但我想学习其他方法。可以使用 map() 方法或 forEach() 来完成吗?怎么样...在声明中?我想用纯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)];

您可以使用

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因为为什么使用"为...在"与数组迭代这么坏的主意?.

如果你有一个现有的数组,你可以使用 map。

var path = [0,1,2].map( x => new Cell(0, x))

或变异

path = path.map( x => {
  x.value = x.yCoordinate - 1
  return x 
}) 
一个简单的

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>