【发布时间】:2016-12-27 16:41:38
【问题描述】:
我是编程新手,我有一个任务要求从一维数组创建一个二维数组。我想出了这个(没有任何外部资源的帮助,因为它带走了学习经验)。它适用于我们的教授测试输入,我只是想知道这是一个丑陋/低效的解决方案。
function twoDArray(arr, lenSubArray) {
var newArr = [];
var placeHolder = 0;
var leftOver = 0;
for (var i = 1; i < arr.length + 1; i++) {
/* if i is a multiple of the specified sub-array size
then add the elements from placeHolder to i
*/
if (i % lenSubArray === 0) {
newArr.push(arr.slice(placeHolder, i));
placeHolder += lenSubArray;
leftOver++; // tells us how many sub-arrays were created
}
}
/* if original array is not divisible by the length of the specified sub-array
then there will be left over values. Retrieve these values and create an
array out of them and add them to the 2d array.
*/
if (!(arr.length % lenSubArray === 0)) {
/* sub-array count multiplied by the length of each
sub-array gives us the right index to retrieve remaining values
*/
leftOver = (leftOver * lenSubArray);
newArr.push(arr.slice(leftOver))
}
return newArr;
}
测试输入:twoDArray([1, 2, 3, 4, 5], 3) 输出将是:[[1, 2, 3], [4, 5]]
【问题讨论】:
-
请添加输入数组和所需输出数组的示例。
-
concat 会给你更简洁的代码。看看这个stackoverflow.com/questions/14824283/…
标签: javascript arrays multidimensional-array