1

我正在尝试遍历所有用户的评论,但使用 if 语句查找某个值。问题是我的应用程序中断,因为一些用户没有发表评论,因此我得到一个“无法读取”未定义的“收集”属性。如何跳过 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>

    <% } %>
4

3 回答 3

2

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

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

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

尝试阅读有关Object.prototype.hasOwnProperty()的更多信息

于 2017-12-14T01:23:49.880 回答
1

只需添加一个检查以查看对象是否存在,以及评论长度是否> 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>

<% } %>
于 2017-12-14T01:22:41.047 回答
0

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

于 2017-12-14T01:22:29.810 回答