2017-10-07 83 views
0

我正在編寫一個程序,允許用戶只能查看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]) 
    } 
    } 

回答

0

有你的代碼少的語法錯誤,它在這裏和那裏缺少一些paranthesis。

您也應該檢查的條件visitorRating[e].indexOf("4 stars") !== -1

DEMO

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]) 
 
    } 
 
}

0

Array#indexOf返回-1如果該項目沒有找到。由於-1不是一個虛假值,所以在if中將其轉換爲true,並且除了索引爲0的索引之外,因爲0被傳送到false,所以您將獲得所有項目。條件更改爲:

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

演示:

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>') 
 
    } 
 
}

相關問題