循环结果并根据距离改变价值

时间:2016-02-03 16:07:37

标签: javascript arrays if-statement

我试图遍历一个对象数组。我想根据距离改变评级。例如,如果距离为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>

1 个答案:

答案 0 :(得分:1)

有些事我觉得你错过了。首先,您遍历每个列表对象,并且永远不会更新评级变量。其次是对象中的距离和评级变量是string而不是int s,因此您的比较和操作将会关闭。在开始时,您可以为对象指定评级和距离,而不是从对象中指定值。

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

&#13;
&#13;
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]);
}
&#13;
&#13;
&#13;