【发布时间】:2016-08-26 10:24:53
【问题描述】:
试图创建一个函数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:
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)
【问题讨论】:
-
你能解释一下你到底想达到什么目标吗?
-
function mCreate(...arg){} -
@PranavCBalan 这只会返回
[2, 2, 2]而不是我所追求的:( -
@cmdv : 你可以得到 n 个参数,然后使用一些方法实现你想要的
-
@RickHitchcock 它将包含 1 个元素
标签: javascript matrix multidimensional-array