比较不同的数组索引Javascript

时间:2020-04-03 00:40:54

标签: javascript ejs

如果[i]索引处的时间表的值等于[i +1]索引处的时间表的值,我正在尝试运行if循环进行编译。但是时间表[i +1]的值总是以未定义的形式返回

<% for(i=0; i < timesheets.length; i++){ %>
            <td><%= timesheets[i][5] %></td>
            <% if(timesheets[i][0] != timesheets[i + 1][0]){ %>
                <% for(a=0; timesheets[a] == timesheets[i]; a++){ %>
                    <% timesheets.splice[a]; %>
                <% } %>
<%}%><%}%>

错误日志:

TypeError: D:\reports\displayTimesheets.ejs:13
    11|         <% for(i=0; i < timesheets.length; i++){ %>
    12|             <td><%= timesheets[i][5] %></td>
 >> 13|             <% if(timesheets[i][0] != timesheets[i + 1][0]){ %>
    14|                 <% for(a=0; timesheets[a] == timesheets[i]; a++){ %>
    15|                     <% timesheets.splice[a]; %>
    16|                 <% } %>

Cannot read property '0' of undefined

1 个答案:

答案 0 :(得分:0)

该错误可能是在循环的最后一遍,达到数组的全长时发生的。那时没有i + 1,因为它是数组的结尾。

您将必须检查自己是否结束

尝试if(timesheets[i+1] && timesheets[i][0] !== timesheets[i+1][0])

这将在尝试访问空时间表上的属性之前检查对象是否存在。

希望这会有所帮助!

相关问题