3 回答
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);
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]));
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]));
添加回答
举报