为什么这个返回[[a,b]],而不是[[a,b],[' c ',' d ']]吗?

时间:2021-10-23 20:46:09

I am doing freecodecamp's Bonfire:Chunky Monkey. I almost have the solution, but I can't figure it out why it isn't working. So my question is: "Why does this return [['a', 'b']], instead of [['a','b'],['c','d']]?

我在做freecodecamp的篝火:厚实的猴子。我几乎找到了解决方案,但我不知道为什么它不能工作。我的问题是:“为什么这个还[[a,b]],而不是[[a,b],[' c ',' d ']]吗?

function chunk(arr, size) {
  var array = [];
  var tmp = [];
  for(var i = 0; i < Math.floor(arr.length/size); i++)
  {
  for(var j = 0; j < size; j++)
    {
      tmp.push(arr[j]);
    }
    array.push(tmp);
    tmp = [];
    arr.splice(0,size);
  }
  return array;
}
chunk(['a', 'b', 'c', 'd'], 2);

5 个解决方案

#1


1  

You are modifying the length of arr on each iteration preventing it from executing the second time.
Besides, one loop is enough.

您正在修改每个迭代中arr的长度,防止它第二次执行。此外,一个循环就足够了。

function chunk(arr, size) {
  var array = [];
  for(var i = 0; i < arr.length; i += size) {
    array.push(arr.slice(i, i + size));
  }
  return array;
}
chunk(['a', 'b', 'c', 'd'], 2);

#2


3  

Because you are altering the length of arr within the loop. As a result, the outer loop only runs once. You need to cache this before you alter it:

因为你正在改变循环中arr的长度。因此,外部循环只运行一次。您需要在修改之前缓存它:

function chunk(arr, size) {
    var array = [];
    var tmp = [];

    // save this, otherwise the 2nd iteration will not run at all 
    // because the new array length will be 2, making half of that 1
    var iter = Math.floor(arr.length / size);

    for (var i = 0; i < iter; i++) {
        for (var j = 0; j < size; j++) {
            tmp.push(arr[j]);
        }
        array.push(tmp);
        tmp = [];
        arr.splice(0, size);
    }
    return array;
}

#3


1  

Another approach:

另一种方法:

function chunk(arr, size) {
 var array = [];
 var tmp = [];
 var aux = 0;
 for(var i = 0; i < Math.ceil(arr.length/size); i++)
 {
   for(var j = aux; j < aux + size; j++)
   {
     arr[j] != undefined?tmp.push(arr[j]):false;
   }
   aux = aux + size;
   array.push(tmp);
   tmp = [];
  }
 return array;
 }
 console.log(chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2));

PS: It works with even and odd number of elements in the array.

它可以处理数组中偶数和奇数的元素。

#4


0  

Plenty of answers with working codes, so I just answer the why.

大量的工作代码的答案,所以我只回答为什么。

You thought the outer loop iterates twice, because Math.floor(arr.length/size) is 2 at the beginning:

您认为外部循环迭代两次,因为Math.floor(arr.length/size)在开头是2:

for(var i = 0; i < Math.floor(arr.length/size); i++) {
    // ....
}

However, arr is chunked in the first iteration:

然而,arr在第一次迭代中是分段的:

arr.splice(0,size); // arr is ['c', 'd'] after this step

For the second iteration, i becomes 1 and Math.floor(arr.length/size) is actually Math.floor(['c', 'd']/2), the check fails and the loop exits. So there isn't a second iteration.

对于第二次迭代,我变成了1和Math.floor(arr.length/size)实际上是数学。在('c', 'd']/2)层,检查失败,循环退出。所以没有第二个迭代。

#5


0  

Configurable chunk size example with a loop.

具有循环的可配置块大小示例。

function chunk(arr, chunkSize) {
  var array = [];

  for (var index = 0, arrLen; index < chunkSize; index++) {
    arrLen = arr.length;
    if (arrLen >= chunkSize) {
      array[index] = arr.splice(0, chunkSize === 1 ? arrLen : chunkSize);
    } else if (arrLen > 0) {
      array[index] = arr.splice(0, arrLen);
    }
  }
  return array;
}

var result = chunk(['a', 'b', 'c', 'd'], 1);
console.log(result);

#1


1  

You are modifying the length of arr on each iteration preventing it from executing the second time.
Besides, one loop is enough.

您正在修改每个迭代中arr的长度,防止它第二次执行。此外,一个循环就足够了。

function chunk(arr, size) {
  var array = [];
  for(var i = 0; i < arr.length; i += size) {
    array.push(arr.slice(i, i + size));
  }
  return array;
}
chunk(['a', 'b', 'c', 'd'], 2);

#2


3  

Because you are altering the length of arr within the loop. As a result, the outer loop only runs once. You need to cache this before you alter it:

因为你正在改变循环中arr的长度。因此,外部循环只运行一次。您需要在修改之前缓存它:

function chunk(arr, size) {
    var array = [];
    var tmp = [];

    // save this, otherwise the 2nd iteration will not run at all 
    // because the new array length will be 2, making half of that 1
    var iter = Math.floor(arr.length / size);

    for (var i = 0; i < iter; i++) {
        for (var j = 0; j < size; j++) {
            tmp.push(arr[j]);
        }
        array.push(tmp);
        tmp = [];
        arr.splice(0, size);
    }
    return array;
}

#3


1  

Another approach:

另一种方法:

function chunk(arr, size) {
 var array = [];
 var tmp = [];
 var aux = 0;
 for(var i = 0; i < Math.ceil(arr.length/size); i++)
 {
   for(var j = aux; j < aux + size; j++)
   {
     arr[j] != undefined?tmp.push(arr[j]):false;
   }
   aux = aux + size;
   array.push(tmp);
   tmp = [];
  }
 return array;
 }
 console.log(chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2));

PS: It works with even and odd number of elements in the array.

它可以处理数组中偶数和奇数的元素。

#4


0  

Plenty of answers with working codes, so I just answer the why.

大量的工作代码的答案,所以我只回答为什么。

You thought the outer loop iterates twice, because Math.floor(arr.length/size) is 2 at the beginning:

您认为外部循环迭代两次,因为Math.floor(arr.length/size)在开头是2:

for(var i = 0; i < Math.floor(arr.length/size); i++) {
    // ....
}

However, arr is chunked in the first iteration:

然而,arr在第一次迭代中是分段的:

arr.splice(0,size); // arr is ['c', 'd'] after this step

For the second iteration, i becomes 1 and Math.floor(arr.length/size) is actually Math.floor(['c', 'd']/2), the check fails and the loop exits. So there isn't a second iteration.

对于第二次迭代,我变成了1和Math.floor(arr.length/size)实际上是数学。在('c', 'd']/2)层,检查失败,循环退出。所以没有第二个迭代。

#5


0  

Configurable chunk size example with a loop.

具有循环的可配置块大小示例。

function chunk(arr, chunkSize) {
  var array = [];

  for (var index = 0, arrLen; index < chunkSize; index++) {
    arrLen = arr.length;
    if (arrLen >= chunkSize) {
      array[index] = arr.splice(0, chunkSize === 1 ? arrLen : chunkSize);
    } else if (arrLen > 0) {
      array[index] = arr.splice(0, arrLen);
    }
  }
  return array;
}

var result = chunk(['a', 'b', 'c', 'd'], 1);
console.log(result);