gpt4 book ai didi

javascript - 循环遍历结果并根据距离改变值

转载 作者:行者123 更新时间:2023-11-27 23:23:29 26 4
gpt4 key购买 nike

我正在尝试循环遍历对象数组。我想根据距离的远近改变评级。例如,如果距离为 10-20 英里,评级就会下降。

这就是我所做的,但我不确定为什么它不起作用,因为我没有收到任何错误。

<script>

var products = [{product:"Shoe", Rating:"4", Distance:"2"},{product:"Trousers", Rating:"5", Distance:"5"},{product:"Glasses", Rating:"3", Distance:"7"},{product:"Hat", Rating:"2", Distance:"10"}];
var rating = products[1];
var distance = products[2];

for (var i=0; i < products.length; i++) {
if (distance >= 0 && distance <=4)
rating = rating+1;
else if (distance >= 5 && distance <=10)
rating = rating-1;
else if (distance >= 11 && distance <=20)
rating = rating-2;
else if (distance >= 21 && distance <=100)
rating = rating-3;
else if (distance >= 101 && distance <=10000)
rating = rating-4;
else
rating = rating;
console.log(products[i]);
}

</script>

最佳答案

我觉得你缺少一些东西。首先是循环遍历每个列表对象并且从不更新评级变量。其次,对象中的距离和评级变量是字符串而不是整数,因此您的比较和操作将关闭。一开始,您将评级和距离分配给对象,而不是对象的值。

我会将变量赋值更改为 for 循环内部的 [i],然后是距离或评级。还有 parseInt,以便您可以将其作为 int 进行比较。然后在每次循环迭代后更新评级。

var products = [{
product: "Shoe",
Rating: "4",
Distance: "2"
}, {
product: "Trousers",
Rating: "5",
Distance: "5"
}, {
product: "Glasses",
Rating: "3",
Distance: "7"
}, {
product: "Hat",
Rating: "2",
Distance: "10"
}];
var rating;
var distance;

for (var i = 0; i < products.length; i++) {
rating = parseInt(products[i]['Rating']);
distance = parseInt(products[i]['Distance']);
if (distance >= 0 && distance <= 4)
rating = rating + 1;
else if (distance >= 5 && distance <= 10)
rating = rating - 1;
else if (distance >= 11 && distance <= 20)
rating = rating - 2;
else if (distance >= 21 && distance <= 100)
rating = rating - 3;
else if (distance >= 101 && distance <= 10000)
rating = rating - 4;
else
rating = rating;
products[i]['Rating']=rating;
console.log(products[i]);
}

关于javascript - 循环遍历结果并根据距离改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35181951/

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