为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MYYA 2022-09-23 21:39:27
我想要一个创建多维数组的函数(纯 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]]提前致谢!!
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

万一您需要这些优化: 性能提示
如果您尝试通过预初始化数组进行优化,请阅读避免创建漏洞

减少正确的方法:

const nestedArray = (...args) => args.reduceRight((arr, length, i) =>

      Array.from({length}, _ => i ? arr : arr.map(x=>[...x])), Array(args.pop()))


let x

console.log(

    x=nestedArray(3,2,4)

)


x[0][0][0]=123


console.log(

    x

)


递归方法:


const nestTriArray = (length, ...args) => {

  if(!args.length) return Array(length)

  return Array.from({length}, _=>[...nestTriArray(...args)])

}


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

console.log(test);



test[0][0][0]=123

console.log(test);


查看完整回答
反对 回复 2022-09-23
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

下面是一个递归实现,可以实现您想要的目标:


function nestArray(arrDims) {

    const [head, ...tail] = arrDims;

    const arr = new Array(head);

    return tail.length > 0 ? arr.fill(0).map(() => nestArray(tail)) : arr;

}


console.log(nestArray([5]));

console.log(nestArray([4, 3, 2]));


查看完整回答
反对 回复 2022-09-23
?
阿晨1998

TA贡献2037条经验 获得超6个赞

这是变体与reduce


[编辑]修复了浅副本和评论。reduceRight


const nestArray = arr =>

  arr.reduceRight((acc, v) => {

    return new Array(v).fill(null).map(()=> acc ? [...acc] : acc);

  }, undefined);

console.log(nestArray([2, 5, 7, 10]));


查看完整回答
反对 回复 2022-09-23
  • 3 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信