尝试创建一个函数 mCreate()
给定一个数字集返回一个多维数组(矩阵):
mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
当此函数仅处理 2 级深度时,即:mCreate(2, 2)//[[0, 0], [0, 0]]
我知道要做 2 级,你可以使用 2 个嵌套的 for 循环
但我遇到的问题是如何处理第 n 个参数。
这个问题是否可以通过递归更好地解决,否则我如何根据参数的数量动态确定我将需要的嵌套 for 循环
的数量?
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"]]]
关于javascript - 在 Javascript 中创建多维数组和矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969154/