我试图从一个数组

时间:2017-03-15 08:00:51

标签: javascript arrays

我试图从一个数组创建新的数组数组

如何制作

var array = [' 1',' 2',' 3',' 4',' 5&#39 ;,' 6',' 7',' 8',' 9',' 10'];

成为

var array = [[' 1',' 2'],[' 3',' 4'],[&# 39; 5',' 6'],[' 7',' 8'],[' 9',' ; 10']];

2 个答案:

答案 0 :(得分:1)

使用带Array#splice方法的简单循环来更新相同的数组。

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2;

// iterate upto the length(which is dynamic)
for (var i = 0; i < array.length; i++)
  // remove the 2 elements and insert as an array element
  // at the same index
  array.splice(i, 0, array.splice(i, size));

console.log(array);

如果您想生成新数组,请使用Array#slice方法。

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2,
  res = [];

// iterate over the array where increment index by the size
for (var i = 0; i < array.length; i += size)
  // push the subarray
  res.push(array.slice(i, i + size));

console.log(res);

采用Array.from方法的ES6替代方案:

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2;

var res = Array.from({
  // create an array of size based on the chunk size
  length: Math.ceil(array.length / size)
  // iterate and generate element by the index
}, (_, i) => array.slice(i * size, i * size + size))

console.log(res);

答案 1 :(得分:1)

尝试以下方法:

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var newArray = [];
var i,j,chunk = 2;
for (i=0,j=array.length; i<j; i+=chunk) {
    newArray.push(array.slice(i,i+chunk));
}
console.log(newArray);