我是编程新手,我有一个作业要求从一维数组创建二维数组。我想出了这个(没有任何外部来源的帮助,因为它剥夺了学习经验)。它适用于我们的教授测试输入,我只是想知道这是一个丑陋/低效的解决方案。
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]]
最佳答案
你太复杂了:
- 创建结果数组
- 将切片从
i
推送到i+lenSubArray
- 将
i
增加lenSubArray
切片足够智能,可以正确处理数组的末尾
function twoDArray(arr, lenSubArray) {
var i = 0, result = [];
while(i < arr.length)
result.push( arr.slice(i, i+=lenSubArray) );
return result;
}
关于javascript - 从一维数组创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057351/