2017-07-03 48 views
1

我有一個循環與內if語句如下如果循環返回null的JavaScript

var html = ""; 
var i; 
for (i = 0; i < products.length; i++) 
{ 
    if(products[i].attrs.product_type == type) 
    { 
    html += '<p>hello world</p>';  
    } 
} 

我真的希望能夠說,如果沒有結果從循環回來,說:「對不起,沒有結果發現」等......我已經試過以下...

for (i = 0; i < products.length; i++) 
{ 
    if(products[i].attrs.product_type == type) 
    { 
    html += '<p>hello world</p>' +i;  
    } 
} 

但是,這只是把旁邊的返回結果的對象數...

任何幫助將是巨大的,因爲我敢肯定,這是非常容易

感謝

+0

在較高水平,你應該做的是在循環之外設置一些等於false/zero的變量,然後在循環內設置爲true/1,並在循環完成後檢查該變量。如果它仍然等於假/零,你就會知道沒有任何東西符合循環條件。 – user2366842

+0

所以如果長度爲零比輸出該消息.....什麼'我'必須做什麼沒有結果? – epascarello

回答

0

類似shotor的答案,但略有不同的方法是如下:

var html = ""; 
var i; 
var found = false; 
for (i = 0; i < products.length; i++) 
{ 
    if(products[i].attrs.product_type === type) 
    { 
    html += '<p>hello world</p>' +i; 
    found = true;  
    } 
}  

if (found === false) 
    { 
    //do stuff here. 
    } 
+1

isTrue = false是一個有趣的var名稱。 –

+0

我將'isTrue'重命名爲'found'。當你檢查'isTrue === false'時真的很混亂。 :) –

+0

調整了名稱。對我來說這是有道理的,但我想這不是世界上最乾淨的命名約定:) – user2366842

2

在最後檢查的html變量是否真正充滿,如果不是我們沒有發現任何項目,我們可以使用惋惜的消息:

var html = ''; 
var i; 
for (i = 0; i < products.length; i++) 
{ 
    if(products[i].attrs.product_type === type) 
    { 
    html += '<p>hello world</p>';  
    } 
}  

if (html === '') { // or: "if (!html)" if you like that sort of thing 
    html = 'Sorry, no results were found' 
} 

還要注意,我改變從=====的比較。這是因爲==試圖轉換類型。而===不。使用===來防止奇怪的錯誤,通常這是你想要的。有關它的詳細信息:Which equals operator (== vs ===) should be used in JavaScript comparisons?

更新,因爲評論由@ASDFGerte

+0

您的代碼似乎在檢查'products'是否具有零長度,而不是循環是否有任何結果。 – ASDFGerte

+0

你說得對。忽略我的答案,直到我更新它。 – shotor

+0

謝謝@ASDFGerte,更新了答案 – shotor

0
var html = ""; 
var i; 
var hasResult = false; 
for (i = 0; i < products.length; i++) 
{ 
    if(products[i].attrs.product_type == type) 
    { 
     html += '<p>hello world</p>'; 
     hasResult = true; 
    } 
} 

if(!hasResult){ 

    html = "No match"; 
}