用于创建多维数组的脚本函数

我想要一个创建多维数组的函数(纯 java 脚本)(没有 jQuery)。


我做了一个完全硬编码的,它限制了我可以深入研究的维度数量。


function nestTriArray(first, second, third){

  const arr = new Array(first);

  for(let i=0; i<first; i++){

    arr[i] = new Array(second);

    for(let j=0; j<second; j++){

      arr[i][j] = new Array(third);

    }

  }

  return arr;

}


const test = nestTriArray(3,2,3);

console.log(test);

输出正确的结果:


//[[[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]]]

我还有另一次尝试尝试在一个函数中使其多维(而不是硬编码第四维,第五维的独立函数......),其中我向函数传递一个数组,数组的长度是维数,每个元素表示每个子数组的长度。它使用递归函数。而且它输出错误。


这是尝试:


function nestArray(conf_array/*first, second, third*/){

  conf_array = [1].concat(conf_array);

  const arr = [];


  let last_in_ref = arr;

  function re(index){

    last_in_ref[conf_array[index]] = new Array(conf_array[index+1]);

    for(let i=0; i<conf_array[index]; i++){

      last_in_ref[i] = new Array(conf_array[index+1]);

    }

    last_in_ref = last_in_ref[index];

    console.log(arr);

    index++;

    if(index < conf_array.length){re(index);}

  }


  re(0);


  return arr;

}


const test = nestArray([3,2,3]);

console.log(test);

输出错误:


//[[[undefined, undefined], [[undefined, undefined, undefined], [undefined, undefined, undefined], [[undefined], [undefined], [undefined], [undefined]]], [undefined, undefined], [undefined, undefined]], [undefined, undefined, undefined]]

提前致谢!!


MYYA
浏览 91回答 3
3回答

MMTTMM

万一您需要这些优化:&nbsp;性能提示如果您尝试通过预初始化数组进行优化,请阅读避免创建漏洞减少正确的方法:const nestedArray = (...args) => args.reduceRight((arr, length, i) =>&nbsp; &nbsp; &nbsp; Array.from({length}, _ => i ? arr : arr.map(x=>[...x])), Array(args.pop()))let xconsole.log(&nbsp; &nbsp; x=nestedArray(3,2,4))x[0][0][0]=123console.log(&nbsp; &nbsp; x)递归方法:const nestTriArray = (length, ...args) => {&nbsp; if(!args.length) return Array(length)&nbsp; return Array.from({length}, _=>[...nestTriArray(...args)])}const test = nestTriArray(3,2,1);console.log(test);test[0][0][0]=123console.log(test);

红糖糍粑

下面是一个递归实现,可以实现您想要的目标:function nestArray(arrDims) {&nbsp; &nbsp; const [head, ...tail] = arrDims;&nbsp; &nbsp; const arr = new Array(head);&nbsp; &nbsp; return tail.length > 0 ? arr.fill(0).map(() => nestArray(tail)) : arr;}console.log(nestArray([5]));console.log(nestArray([4, 3, 2]));

阿晨1998

这是变体与reduce[编辑]修复了浅副本和评论。reduceRightconst nestArray = arr =>&nbsp; arr.reduceRight((acc, v) => {&nbsp; &nbsp; return new Array(v).fill(null).map(()=> acc ? [...acc] : acc);&nbsp; }, undefined);console.log(nestArray([2, 5, 7, 10]));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript