创建多维数组Javascript中的矩阵 [英] Creating multidimensional arrays & matrices in Javascript
问题描述
尝试创建给定数字的函数mCreate()
会返回多维数组(矩阵):
Trying to create a function mCreate()
that given a set a numbers returns a multidimensional array (matrix):
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个参数
When this functions handles just 2 levels of depth ie: mCreate(2, 2) //[[0, 0], [0, 0]]
I know to do 2 levels, you can use 2 nested for loops
but the problem I'm having is how to handle an n'th number of arguments.
使用递归是否可以更好地解决此问题,否则在给定参数数量的情况下,如何动态确定需要使用的嵌套for loops
数量?
Would this problem be better approached with recursion, otherwise how can I dynamically determine the number of nested for loops
I'm going to need given the number of arguments?
ps:最有效的方法很棒,但不是必不可少的
ps: the most performant way would be great but not essential
重新编辑-使用Benchmark.js检查性能之后,结果如下:
RE-EDIT - After using Benchmark.js to check perf the results were as follows:
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 :
@briancavalier also came up with a good solution 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中):
One simple recursive answer is this (in ES2015):
const mCreate = (...sizes) =>
Array.from({ length: sizes[0] }, () =>
sizes.length === 1 ? 0 : mCreate(...sizes.slice(1)));
我想我会用一个高阶函数添加初始化器:
I think I'd add the initializer in with a higher order function though:
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中的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!