在Javascript中从数组中删除空数组

时间:2016-12-31 03:46:06

标签: javascript arrays

我有一个数组outer_array。我尝试在outer_array内推送一些数组。但是一些推送的数组是空的。我不想要那些空阵列。我可以手动删除它,但我需要从循环中删除它。这是我的代码:

var ary = [1, 2, 3, 4, 5, 6];
var splitLength = 3;
var outer_lis = [];
var first_limit = 0;
var second_limit = splitLength;
for (var i=0; i<ary.length; i++) {
  outer_lis.push(ary.slice(first_limit, second_limit));
  first_limit += splitLength;
  second_limit += splitLength;
}
console.log(outer_lis);

// Result
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [], [], [], [] ]

我搜索了一个解决方案但我在php得到了结果。我不明白php。如果你能给我一个解决这个问题的解决方案,我非常感激。因为我是Javascript的初学者。

4 个答案:

答案 0 :(得分:2)

感谢dandavis,我得到了解决方案。我改变了这样的代码:

...
for (var i=0; i < ary.length / splitLength; i++) {
  outer_lis.push(ary.slice(first_limit, second_limit));
  first_limit += splitLength;
  second_limit += splitLength;
}
...

现在我得到了我预期的结果。

// Result
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

答案 1 :(得分:1)

// At the class level
let originalHeight = someView.heightConstraint.constant

// At the method level, toggle
someView.heightConstraint.constant = (fullHeight) ? originalHeight : 0

答案 2 :(得分:0)

试试这个,它将帮助您实现没有空数组的结果。在此代码中,您还可以更改splitLength值。

&#13;
&#13;
var ary = [1, 2, 3, 4, 5, 6];
var splitLength = 3;
var outer_lis = [];
var first_limit = 0;
var second_limit = splitLength;
var looplimit = Math.ceil(ary.length / splitLength);
alert(looplimit);
for (var i = 0; i < looplimit; i++) {
  outer_lis.push(ary.slice(first_limit, second_limit));
  first_limit += splitLength;
  second_limit += splitLength;
}
console.log(outer_lis);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

解决方案很简单。这是代码

&#13;
&#13;
var ary = [1, 2, 3, 4, 5, 6, 4],
        splitLength = 3,
        outer_lis = [],
        first_limit = 0,
        second_limit = splitLength,
        length = ary.length,
        totalSubArrays = Math.ceil(length/splitLength);

for (var i = 0; i < totalSubArrays; i++) {
  outer_lis.push(ary.slice(first_limit, second_limit));
  first_limit += splitLength;
  second_limit += splitLength;
}
console.log(outer_lis);
&#13;
&#13;
&#13;