【发布时间】:2019-08-28 21:38:33
【问题描述】:
我想将每次迭代放入主数组中的一个数组中。
像这样:array = [[a,b], [c,d], [e,f]]
push方法与切片、拼接
var descendants = [A,C,C,D,C,B],
chunk = 2,
descendantPairs = [];
for (var i = 0; i < descendants.length; i += chunk) {
descendantPairs = descendantPairs.push(descendants.slice(i, i + chunk));
console.log("descendantPairs: " + descendantPairs});
}
现在我能够得到这样的对,但我需要对所有对执行更多逻辑,而不仅仅是最后一对,因此我需要一个包含所有对的数组。
我现在在 console.log 中得到了这个:
descendantPairs: A,C
descendantPairs: C,D
descendantPairs: C,B
【问题讨论】:
-
descendantPairs = descendantPairs.push(descendants.slice(i, i + chunk));??? -
@MarkMeyer 需要保持后代的顺序,成对,即array = [ [A,C], [C,D], [D,C]]
-
不要用 push() 的结果覆盖整个变量
-
为什么你不使用
if (value%2 == 0)(偶数)
标签: javascript arrays for-loop