我使用下面的函数解决了来自FreeCodeCamp的算法挑战,但我想知道这是否是一个好的"解决问题的方法,最具体地说,因为我将我的计数器设置为i + = 0并从头部拼接索引。我在这里创建了一个反模式吗?有什么更合乎逻辑的,你能解释一下原因吗?提前感谢您的帮助!
function chunk(arr, size) {
var newArr = [];
for (i=0; i<arr.length; i+=0) {
var sliced = arr.slice(i, size);
newArr.push(sliced);
arr.splice(0, size);
}
return newArr;
}
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]
答案 0 :(得分:1)
也许是递归?
function chunk(arr, size, out) {
// if the output array hasn't been passed in
// create it
out = out || [];
// if there are no elements in the input array
// return the output array
if (!arr.length) return out;
// push the "head" of the input array to the
// output array
out.push(arr.slice(0, size));
// call chunk again with the "tail" of the input array
return chunk(arr.slice(size), size, out);
}
答案 1 :(得分:1)
我在这里创建了一个反模式吗?有什么更合乎逻辑的,你能解释一下原因吗?
您的代码包含一些可改进的部分
function chunk(arr, size) {
//newWhatever, myWhatever, ... look for a better naming like `out` or `result`
//or in this case `chunks` would describe the content of the variable
var newArr = [];
//you initialize `i` without the var-keyword, therefore you populate/pollute the global namespace
//and instead of calculating i+=0, you can leave this part empty:
//for(var i=0; i<arr.length; ){
for (i=0; i<arr.length; i+=0) {
var sliced = arr.slice(i, size);
newArr.push(sliced);
//splicing (with P) is often a thing that should be avoided,
//- it is destructive (it destroys the input-array)
//- it is slow, cause the engine has to allocate new memory
// and copy the remaining elements over to this memory,
// and garbage-collect the old memory
arr.splice(0, size);
}
return newArr;
}
更好的解决方案是:
function chunk(arr, size) {
for(var chunks=[], i=0; i<arr.length; i+=size)
chunks.push(arr.slice(i, size));
return chunks;
}
假设输入正确。
对于completenes,您应该添加一些输入验证。那个arr到位,可以切片,并且具有长度属性 并且该大小是整数&gt; 0否则代码可能会产生奇怪的结果。
function chunk(arr, size) {
//checks if arr is not empty and arr.slice is not empty
//and casts the length-property to int
//if anything "fails" len = 0;
var len = (arr && arr.slice && arr.length)|0;
//check if size is > 1 and is an integer
if(size !== Math.floor(size) || size < 1)
throw new Error("invalid chunl-size: "+size);
for(var chunks=[], i=0; i<len; i+=size)
chunks.push(arr.slice(i, size));
return chunks;
}
答案 2 :(得分:0)
function chunk(arr, size) {
var subArrayCount = arr.length / size;
var res = [];
for (i = 0; i < subArrayCount; i++) {
var from = size * i;
var to = (size * (1 + i));
console.log(to)
var sliced = arr.slice(from, to);
res.push(sliced);
}
return res;
}
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]