简体   繁体   English

push() 方法在 JavaScript 中无法正常工作

[英]push() method not working properly in JavaScript

I'm trying to write a quite simple program that divides an array in another array of defined size smaller arrays, however the push() method is not working.我正在尝试编写一个非常简单的程序,将一个数组划分为另一个定义大小较小的数组 arrays,但是push()方法不起作用。 Could someone please help me with it?有人可以帮我吗?

function chunk(array, size) {
  var newArray = [];
  var tempArray = [];

  for (let i = 0; i < array.length / size; i++) {
    for (let j = size * i, k = 0; j < size * i + size; j++, k++)
      tempArray[k] = array[j];

    newArray.push(tempArray);
  }

  return newArray;
}

var data = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(chunk(data, 2));

The ideal output should be [[1, 2],[3, 4], [5, 6], [7, 8]] .理想的 output 应该是[[1, 2],[3, 4], [5, 6], [7, 8]] However im getting [[7,8],[7,8],[7,8],[7,8]] .但是我得到[[7,8],[7,8],[7,8],[7,8]]

You're almost there.你快到了。 Just move the tempArray definition inside your first for -loop.只需将tempArray定义移动到第一个for循环中。 Otherwise you would be pushing the same array each time.否则你每次都会推同一个数组。

Working Example:工作示例:

 function chunk(array, size) { const newArray = []; for (let i = 0; i < array.length / size; i++) { const tempArray = []; for (let j = size * i, k = 0; j < size * i + size; j++, k++) tempArray[k] = array[j]; newArray.push(tempArray); } return newArray; }; const data = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(chunk(data, 2)); // [[1, 2],[3, 4], [5, 6], [7, 8]]

@Behemoth's answer is the correct one for the question . @Behemoth 的回答是对问题的正确回答 But if you want, you can take a slightly different approach like this to reach the solution as well.但是,如果您愿意,您也可以采用类似这种略有不同的方法来获得解决方案。

 function chunk(array, size){ const newArray = []; let i,j; for (i = 0,j = array.length; i < j; i += size) { newArray.push(array.slice(i, i + size)); } return newArray; }; var data = [1, 2, 3, 4, 5, 6, 7,8]; console.log(chunk(data, 2));

Slightly different solution than @Behemoth and @Rukshan与@Behemoth 和@Rukshan 略有不同的解决方案

 function chunk(array, size) { var newArray = []; var tempArray = []; for (let i = 0; i < array.length / size; i++) { for (let j = i; j < i + 1; j++) { for (let k = 0; k < size; k++) { if (array[size * j + k]) { tempArray.push(array[size * j + k]); } } newArray.push(tempArray); tempArray = []; } } return newArray; }; var data = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(chunk(data, 2));

The solution would be [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ] instead of [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ]]解决方案是 [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ] 而不是 [ [ 1, 2 ], [ 3, 4 ], [ 5 , 6 ], [ 7, 8 ]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM