尝试创建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:最有效的方法很棒,但不是必需的
重新编辑-使用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)
一个简单的递归答案是这样的(在ES2015中):
const mCreate = (...sizes) =>
Array.from({ length: sizes[0] }, () =>
sizes.length === 1 ? 0 : mCreate(...sizes.slice(1)));
编辑:我想我会以一个更高阶的函数添加初始化程序:
const mCreate = (...sizes) => (initialValue) =>
Array.from({ length: sizes[0] }, () =>
sizes.length === 1 ? initialValue : mCreate(...sizes.slice(1))(initialValue));
可以这样使用:
mCreate(2, 2, 2)('hi');
// [[["hi", "hi"], ["hi", "hi"]], [["hi", "hi"], ["hi", "hi"]]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句