简体   繁体   English

如何在for循环中访问子数组的长度?

[英]How to access sub array length inside a for loop?

I have a 2D array that I am trying to manipulate/merge similar entries. 我有一个2D数组,我试图操纵/合并类似的条目。 I push -1 on the 3rd index of the arrays I am marking for delete. 我在要标记为删除的数组的第三个索引上按-1 Here is a sample of rowArray : 这是rowArray的示例:

[
   [44,16,0,-1],
   [44,16,1,-1],
   [44,16,0]
]

In my for-loop, I decrement through the array and if rowArray[i][3] exists I am trying to pop this array from the matrix. 在我的for循环中,我递减了数组,如果rowArray[i][3]存在,我试图从矩阵中弹出该数组。 My problem is that in my if i'm always receiving a problem. 我的问题是, if我总是遇到问题。 When I use: 当我使用时:

if( rowArray[i][3] ).. or if( rowArray[i][3] !== 'undefined').. etc. then I receive a TypeError: if( rowArray[i][3] )..if( rowArray[i][3] !== 'undefined')..等。然后我收到TypeError:

Uncaught TypeError: Cannot read property 'length' of undefined

I have also tried using: 我也尝试过使用:

if( rowArray[i].length > 3 ) but this gives me the error: Uncaught TypeError: Cannot read property 'length' of undefined if( rowArray[i].length > 3 )但这给了我错误: Uncaught TypeError: Cannot read property 'length' of undefined

Here is my code: 这是我的代码:

  rowArray = [ [44, 16, 0, -1], [44, 16, 1, -1], [44, 16, 0] ]; for (var i = 1; i < rowArray.length; i++) { if (rowArray[parseInt(i - 1)][0] == rowArray[i][0] && rowArray[parseInt(i - 1)][1] == rowArray[i][1]) { rowArray[i][2] += parseFloat(rowArray[parseInt(i - 1)][2]); rowArray[parseInt(i - 1)][3] = -1; } } for (var i = rowArray.length; i >= 0; i--) { console.log(rowArray[i].length); if (rowArray[i][3] !== 'undefined') { rowArray.splice(i, 1); } } 

Expected Output: 预期产量:

[[44,16,1]]

I should mention that I am using jQuery 3.4.0. 我应该提到我正在使用jQuery 3.4.0。 Also open to better solutions to this problem (as always). 也一如既往地寻求更好的解决方案。

The problem is that in the second loop you are starting from the rowArray.length which is not right because the last item is rowArray.length-1 . 问题是在第二个循环中,您是从rowArray.length开始的,该rowArray.length是不正确的,因为最后一项是rowArray.length-1 That's because the array starts from 0. So your second loop would be like this: 那是因为数组从0开始。所以第二个循环是这样的:

for (var i = rowArray.length-1; i >= 0; i--) {
   console.log(rowArray[i].length);
   if (rowArray[i][3] !== 'undefined') {
     rowArray.splice(i, 1);
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM