我在js中有构造函数:
function car (){
this.name=name;
this.position=position;
}
我从上面的构造函数创建了两个obj并推送到数组:
arr = [ car{name:car1;position:1},
car{name:car2;position:2} ]
我有另一个数组:
map = ["***","car1","***","car2","***"]
我要它:
for (i = 0; i < arr.length; i++){
if(map[i] !== "***"){ //for example i=1 and map[1] is car1 and i dont know it!
//i need select car with name = car1 and change this car's position to 10
}
}
我不想搜索“ car1”。因为在我的主代码中,当新车(car3)进入car1位置时,car1.position必须为0。确实在地图car的名称中根据cars的位置插入。
最佳答案
我需要选择名称为car1的汽车并更改其位置
至10
下面应该可以帮助您
map = ["***", "car1", "***", "car2", "***"];
arr = [{
name: 'car1',
position: 1
},
{
name: 'car2',
position: 2
}
]
for (i = 0; i < arr.length; i++) {
if (map[i] !== "***") {
const index = arr.findIndex(x => x.name == map[i]);
arr[index].position = 10;
}
}
console.log(arr)