如果for循环返回null javascript

时间:2017-07-03 16:12:52

标签: javascript for-loop

我有一个内部if语句的循环如下

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

我真的很想能说如果for循环没有返回任何结果,说“对不起,没有找到结果”等等......我试过以下......

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

但是这只是将对象编号放在返回的结果旁边......

任何帮助都会很棒,因为我确信这很容易

由于

3 个答案:

答案 0 :(得分: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

的评论而更新

答案 1 :(得分: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.
  }

答案 2 :(得分: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";
}