2016-03-08 22 views
0

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

因此,例如,路径[0] .value的= 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)];

+0

为什么不直接使用一个简单的正'for'环 - >'为(VAR I = 0;我<100;我++){路径。 push(new Cell(0,i))};' – adeneo

+0

'forEach'仅仅是'for'循环中的一种糖。你可以使用任何其他数组方法('map','filter'等),但是你不会正确使用它们。 –

+0

我正在寻找最有效的方法。这是一个for循环? – fatblacklip

回答

0

如果您有现成的数组,你可以使用地图。

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

或变异

path = path.map(x => { 
    x.value = x.yCoordinate - 1 
    return x 
}) 
+0

第二种是只是滥用'地图'虽然。它可能是'forEach'或'filter'。 –

+0

我不同意,它是如何滥用地图?我们从一套开始,然后将其转换为一套新套件。那是什么地图。 – Fresheyeball

+0

在您编辑之前,您专门使用map来迭代一组。你最近的编辑实际上将它变成一个数字数组。 –

0

一个简单的for循环应该工作:

var path = [], 
    len = 10; 

for (
    var idx = 0; 
    idx < len; 
    path.push(new Cell(0,++idx)) 
) 
0
<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

这更多地属于显示。我的脚本依赖于每个单元格的值。 – fatblacklip

+0

你是对的。根据你的问题,我公开了一个使用forEach的例子。 –