cmd*_*mdv 5 javascript matrix multidimensional-array
尝试创建一个mCreate()
给定数字集的函数返回一个多维数组(矩阵):
mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
Run Code Online (Sandbox Code Playgroud)
当这个函数只处理2个级别的深度时,即:mCreate(2, 2) //[[0, 0], [0, 0]]
我知道要做2个级别,你可以使用2个嵌套for loops
但我遇到的问题是如何处理第n个参数.
使用递归更好地解决这个问题,否则我如何根据参数的数量动态确定for loops
我将需要的嵌套数量?
ps:性能最好的方式很棒,但不是必需的
重新编辑 - 使用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
Run Code Online (Sandbox Code Playgroud)
@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)
Run Code Online (Sandbox Code Playgroud)
一个简单的递归答案就是这个(在ES2015中):
const mCreate = (...sizes) =>
Array.from({ length: sizes[0] }, () =>
sizes.length === 1 ? 0 : mCreate(...sizes.slice(1)));
Run Code Online (Sandbox Code Playgroud)
编辑:我想我会用更高阶函数添加初始化器:
const mCreate = (...sizes) => (initialValue) =>
Array.from({ length: sizes[0] }, () =>
sizes.length === 1 ? initialValue : mCreate(...sizes.slice(1))(initialValue));
Run Code Online (Sandbox Code Playgroud)
可以使用如下:
mCreate(2, 2, 2)('hi');
// [[["hi", "hi"], ["hi", "hi"]], [["hi", "hi"], ["hi", "hi"]]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
336 次 |
最近记录: |