首页 > 解决方案 > 如何将数组更改为(mxn)数组

问题描述

例如,如何将数组(向量)更改[1, 2,...,16][[1,2,3,4],..., [13, 14, 15, 16]]. 我写

function IntoMatrix(m,n, array){
temp = [];
Temp = [];
for (j=0; j<array.length; j+=m){
  for (i=0; i<n; i++){
   temp.push(array[i+j]);
    }
    Temp.push(temp);
  }
  return Temp;
}

但肯定有问题。您认为我应该使用inconcat代替push方法Temp吗?

标签: javascript

解决方案


对于每个内部 for 循环,您需要重置temp=[].

function IntoMatrix(m,n, array){
temp = [];
Temp = [];
for (j=0; j<array.length; j+=m){
temp = [];
    for (i=0; i<n; i++){
     temp.push(array[i+j]);
        }
        Temp.push(temp);
    }
    return Temp;
}

console.log(IntoMatrix(4,4,[1,2,3,4,5,6,7,8]));


推荐阅读