如果循环返回null的JavaScript

如果循环返回null的JavaScript

问题描述:

我有一个循环与内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

类似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

在最后检查的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

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"; 
}