假设我有一个这样的 JS 数组:
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
我想把这个数组分成 N 个更小的数组,例如:
split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]
For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]
For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
对于 Python,我有这个:
def split_list_in_n(l, cols):
""" Split up a list in n lists evenly size chuncks """
start = 0
for i in xrange(cols):
stop = start + len(l[i::cols])
yield l[start:stop]
start = stop
对于 JS 来说,我能想到的最好的解决方案是一个递归函数,但我不喜欢它,因为它复杂而丑陋。这个内部函数返回一个像这样的数组[1,2,3,null,4,5,6,null,7,8] ,然后我必须再次循环并手动拆分它。(我的第一次尝试是返回: [1,2,3,[4,5,6,[7,8,9]]] ,我决定使用空分隔符)。
function split(array, cols) {
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));
}
下面是一个简单的例子: http://jsfiddle.net/uduhH/
你怎么做到的,谢谢!