尝试创建一个名为
当此函数仅处理2层深度时,例如:
这个问题最好用递归方法解决,否则如何动态确定需要多少个嵌套的
注:最高效的方法很好,但不是必要的。
RE-EDIT - 使用Benchmark.js检查性能后,结果如下:
mCreate()
的函数,该函数接收一组数字并返回一个多维数组(矩阵):mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
当此函数仅处理2层深度时,例如:
mCreate(2, 2) //[[0, 0], [0, 0]]
。我知道可以使用2个嵌套的for循环
来处理2层深度,但问题是如何处理第n个参数。这个问题最好用递归方法解决,否则如何动态确定需要多少个嵌套的
for循环
,取决于所需参数的数量?注:最高效的方法很好,但不是必要的。
RE-EDIT - 使用Benchmark.js检查性能后,结果如下:
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:
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)
math.zeros(2,2,2)
但具有添加第n个值的能力。这是用于矩阵的。http://mathjs.org/docs/datatypes/matrices.html - cmdv