尝试创建一个函数mCreate()
给定一组数字返回一个多维数组(矩阵):
mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
当此函数仅处理 2 个深度级别时,即:mCreate(2, 2) //[[0, 0], [0, 0]]
我知道要做 2 个级别,你可以使用 2 个嵌套for loops
但我遇到的问题是如何处理第 n 个参数。
这个问题是否可以通过递归更好地解决,否则我如何动态确定嵌套的数量for loops
我需要给出参数的数量?
ps:最高效的方式固然很好,但不是必需的
RE-EDIT- 使用Benchmark.js检查perf后,结果如下:
BenLesh x 82,043 ops/sec ±2.56% (83 runs sampled)
Phil-P x 205,852 ops/sec ±2.01% (81 runs sampled)
Brian x 252,508 ops/sec ±1.17% (89 runs sampled)
Rick-H x 287,988 ops/sec ±1.25% (82 runs sampled)
Rodney-R x 97,930 ops/sec ±1.67% (81 runs sampled)
Fastest is Rick-H
@briancavalier也想出了一个很好的解决方案JSbin http://jsbin.com/mufugu/edit?js,console:
const mCreate = (...sizes) => (initialValue) => _mCreate(sizes, initialValue, sizes.length-1, 0)
const _mCreate = (sizes, initialValue, len, index) =>
Array.from({ length: sizes[index] }, () =>
index === len ? initialValue : _mCreate(sizes, initialValue, len, index+1))
mCreate(2, 2, 2)(0)