while
转换数组只需要一个简单的循环。
// This is the original data we get from the server
var input = ["computer","program","laptop","monitor","mouse","keybord","cpu","harddrive"];
// Make a copy of the input, so we don't destroy it
var data = input.slice(0);
// This is our output array
var output = [], group;
// A while loop will transform the plain array into a multidimensional array
while (data.length > 0) {
// Take the first four items
group = data.splice(0, 4);
// Make sure the group contains 4 items, otherwise pad with empty string
while (group.length < 4) {
group.push("");
}
// Push group into the output array
output.push(group);
}
// output = [["computer","program","laptop","monitor"],["mouse","keybord","cpu","harddrive"]]
更新:Beetroot-Beetroot 的评论不再有效,因为我们创建了输入的副本。