根据用户在提醒

时间:2017-10-07 17:35:49

标签: javascript arrays for-loop while-loop

我正在尝试编写一个程序,允许用户只查看4星评级的酒店。每当我运行此代码时,我都会继续收回阵列中的所有对象,而不仅仅是希尔顿'和'假日酒店'。我究竟做错了什么?感谢。

     var hotels = ['Marriot', 'Hilton', 'Double Tree', 'Holiday Inn']
    var visitorRating = ['0 starts', '4 stars', '1 star', '4 stars']

    var seeHotels = prompt("Would you like to see all of the hotels whose ratings are 4 stars?");
    var fourStars = e;

    for(var e = 0; e < visitorRating.length; e++){
if(visitorRating[e].indexOf("4 stars"))
   document.write( hotels[e] + ' ' + visitorRating[e])
    }
    }

2 个答案:

答案 0 :(得分:0)

如果找不到该项,则

Array#indexOf会返回-1。由于-1不是假值,因此在if中它被翻译为true,并且除了索引为0的项目之外,您将获得所有项目,因为0是转移到false。将条件更改为:

visitorRating[e].indexOf("4 stars") !== -1

<强>演示:

&#13;
&#13;
var hotels = ['Marriot', 'Hilton', 'Double Tree', 'Holiday Inn']
var visitorRating = ['0 starts', '4 stars', '1 star', '4 stars']

for (var e = 0; e < visitorRating.length; e++) {
  if (visitorRating[e].indexOf("4 stars") !== -1) {
    document.write(hotels[e] + ' ' + visitorRating[e] + '<br>')
  }
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码几乎没有语法错误,它在这里和那里都缺少一些问题。

此外,您应该检查条件visitorRating[e].indexOf("4 stars") !== -1

<强>样本

&#13;
&#13;
var hotels = ['Marriot', 'Hilton', 'Double Tree', 'Holiday Inn'];
var visitorRating = ['0 starts', '4 stars', '1 star', '4 stars'];

 var seeHotels = prompt("Would you like to see all of the hotels whose ratings are 4 stars?");
    var fourStars = e;

for(var e = 0; e < visitorRating.length; e++){
if(visitorRating[e].indexOf("4 stars") !== -1){
   document.write( hotels[e] + ' ' + visitorRating[e])
    }
}
&#13;
&#13;
&#13;