gpt4 book ai didi

javascript - 在javascript中根据键值条件选择对象

转载 作者:行者123 更新时间:2023-11-28 03:04:57 26 4
gpt4 key购买 nike

我在 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。实际上在 map 中汽车的名称根据汽车的位置插入。

最佳答案

I need to select a car with name = car1 and change this car's position to 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)

关于javascript - 在javascript中根据键值条件选择对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60692263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com