更改数组中每个项的属性
Change properties of every item in an array?
我需要设置这个数组中每个项目的值,向上计数。
因此,例如,路径[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>
相关文章:
- 如何在不链接/jquery的情况下使用方法应用css属性数组
- 如何使用lodash返回与模式匹配的属性数组
- 从嵌套属性数组中获取对象嵌套值
- 如何使用 javascript 返回数据属性数组
- JQuery 获取返回的属性数组
- 对公共属性数组进行排序
- Angularjs-ng repeat不反映属性数组中的更改
- JADE&NodeJS访问JSON对象属性数组
- Lodash 按数组的属性数组过滤
- 将对象数组转换为属性数组
- 如何从一个共享属性的jQuery集合中获取一个属性数组
- 骨干移除和新视图不会重置其属性数组内容
- 使用JSON从对象数组创建属性数组
- 将数据属性数组转换为对象
- 从属性数组和匹配属性值数组创建JavaScript对象的有效方法
- 访问json中的属性数组
- jquery.获得没有重复的自定义属性数组
- 如何更新对象属性数组值
- 多属性数组语法
- jQuery:生成"name”;动态属性数组