代码之家  ›  专栏  ›  技术社区  ›  Adam Furniss

跳过if语句和循环中未定义的值

  •  1
  • Adam Furniss  · 技术社区  · 7 年前

    我试图遍历所有用户的评论,但使用if语句查找特定值。问题是我的应用程序中断了,因为一些用户没有发表评论,所以我得到了一个未定义的“collected”的“cannot read”属性。如何跳过if语句的未定义值?代码如下:

    <% for(var i=0; i < users.length; i++) { %>
       <tr>
    
    
        <% if(users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>
    
         <td>Nothing in reception - well done!</td>
    
        <%  } else { %>
    
    
    
         <td><%= users[i].studio %></td>
         <td><%= users[i].name %></td>
         <td><%= users[i].email %></td>
         <td><%= users[i].username %></td>
         <td><%= users[i].comments.slice(-1)[0].collected %></td>
    
         <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>
    
        <% } %>
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   John Rey M. Baylen    7 年前

    首先使用以下代码行检查该属性是否可用于该对象:

    yourObject.hasOwnProperty('collected') // it will return true if exist, false if not.

    if(yourObject.hasOwnProperty('collected')) {
      // code here...
    } else {
      // catch here...
    }
    

    尝试阅读有关 Object.prototype.hasOwnProperty()

        2
  •  1
  •   Matt Spinks    7 年前

    只需添加一个检查,查看对象是否存在,以及注释长度是否为>0:

    <% for(var i=0; i < users.length; i++) { %>
       <tr>
    
        <% if(!users[i].comments || users[i].comments.length == 0) {
              continue;
        } else if(users[i].comments && users[i].comments.length > 0 && users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>
    
         <td>Nothing in reception - well done!</td>
    
        <%  } else { %>
      <% console.log('nothing in reception') %>
    
     <td><%= users[i].studio %></td>
     <td><%= users[i].name %></td>
     <td><%= users[i].email %></td>
     <td><%= users[i].username %></td>
     <td><%= users[i].comments.slice(-1)[0].collected %></td>
    
     <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>
    
    <% } %>
    
        3
  •  0
  •   user7452246 user7452246    7 年前

    你试过了吗 continue; ? 我知道你可以把它放在某个街区的某个地方。如果它不符合您的条件标准,它将跳过并迭代到下一个注释/列表。

    推荐文章