JavaScript 4D 数组

发布于 2024-11-08 19:36:17 字数 94 浏览 0 评论 0原文

有人有创建 4D 数组(或任意数量的维度)的函数吗?

我想调用该函数,然后我可以执行类似 arr[3][2][23][12] = "awesome"; 的操作

Anyone have a function to create 4D arrays (or any number of dimensions for that matter)?

I'd like to call the function, then after that I can do something like arr[3][2][23][12] = "awesome";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

蓝礼 2024-11-15 19:36:18

快速而肮脏:

var arr = [[[[[]]]]];

查看http://jsfiddle.net/MJg9Y/

注意: 您仍然需要初始化每个维度。上面的代码为 arr[0] 处的 4 维数组创建了基础。

Quick and dirty:

var arr = [[[[[]]]]];

Check it out http://jsfiddle.net/MJg9Y/

Note: You will still need to initialize each dimension. The above creates the foundation for a 4 dimension array at arr[0].

所有深爱都是秘密 2024-11-15 19:36:18

这是一个简单的递归解决方案。真正的大脑是 mdim 函数。如果深度不为 1,它只会调用自身,并且当它到达那里时,只会返回一个空数组。

因为看起来您可能想将其用于很多事情,所以我将其包装在 Array 的原型中,以便您可以自动在数组上使用它(方便/可维护性权衡)。如果您愿意,可以从闭包中取出 mdim 函数,它应该可以正常工作。

最后有一个简单的测试用例,您可以了解如何使用它。祝你好运! :)

//adds a multidimensional array of specified depth to a given array
//I prototyped it off of array for convenience, but you could take 
//just the mdim function
Array.prototype.pushDeepArr = function( depth ){
    var arr = (mdim = function( depth ){
        if( depth-- > 1 ){
            return [ mdim( depth ) ];
        } else {
            return [];
        }
    })(depth);
    this.push(arr);
};

//example: create an array, add two multidimensional arrays
//one of depth 1 and one of depth 5
x = [];
x.pushDeepArr(1);
x.pushDeepArr(5);

Here's a simple recursive solution. The real brains is the mdim function. It just calls itself if the depth isn't 1, and when it gets there just returns an empty array.

Since it seems like you might want to use this for a lot of things, I've wrapped it in a prototype off of Array so that you can use it on your arrays automatically (convenience/maintainability tradeoff). If you prefer, grab the mdim function out of the closure and it should work just fine.

There's a simple test case at the end so you can see how to use it. Good luck! :)

//adds a multidimensional array of specified depth to a given array
//I prototyped it off of array for convenience, but you could take 
//just the mdim function
Array.prototype.pushDeepArr = function( depth ){
    var arr = (mdim = function( depth ){
        if( depth-- > 1 ){
            return [ mdim( depth ) ];
        } else {
            return [];
        }
    })(depth);
    this.push(arr);
};

//example: create an array, add two multidimensional arrays
//one of depth 1 and one of depth 5
x = [];
x.pushDeepArr(1);
x.pushDeepArr(5);
动次打次papapa 2024-11-15 19:36:18

只需将现有数组中的每个值设置为等于新数组,即可包含所需的元素数量。

请参阅本教程了解一些很好的示例。您可以对任意数量的维度执行此操作。

var myArray = new Array(3);

for (var i = 0; i < 3; i++) {
    myArray[i] = new Array(3);
    for (var j = 0; j < 3; j++) {
        myArray[i][j] = '';
    }
}

Just set each value in an existing array equal to a new array, with however many elements you need.

See this tutorial for some good examples. You can do this with any number of dimensions.

var myArray = new Array(3);

for (var i = 0; i < 3; i++) {
    myArray[i] = new Array(3);
    for (var j = 0; j < 3; j++) {
        myArray[i][j] = '';
    }
}
你曾走过我的故事 2024-11-15 19:36:18

更新
修正了之前功能的一些问题;这似乎可以解决问题:

function multidimensionalArray(){
    var args = Array.prototype.slice.call(arguments);

    function helper(arr){
        if(arr.length <=0){
            return;
        }
        else if(arr.length == 1){
            return new Array(arr[0]);
        }

        var currArray = new Array(arr[0]);
        var newArgs = arr.slice(1, arr.length);
        for(var i = 0; i < currArray.length; i++){
            currArray[i] = helper(newArgs);
        }
        return currArray;
    }

    return helper(args);
}

用法

var a = multidimensionalArray(2,3,4,5);

console.log(a); //prints the multidimensional array
console.log(a.length); //prints 2
console.log(a[0].length); //prints 3
console.log(a[0][0].length); //prints 4
console.log(a[0][0][0].length); //prints 5

Update
Corrected some issues with the previous function; this seems to do the trick:

function multidimensionalArray(){
    var args = Array.prototype.slice.call(arguments);

    function helper(arr){
        if(arr.length <=0){
            return;
        }
        else if(arr.length == 1){
            return new Array(arr[0]);
        }

        var currArray = new Array(arr[0]);
        var newArgs = arr.slice(1, arr.length);
        for(var i = 0; i < currArray.length; i++){
            currArray[i] = helper(newArgs);
        }
        return currArray;
    }

    return helper(args);
}

Usage

var a = multidimensionalArray(2,3,4,5);

console.log(a); //prints the multidimensional array
console.log(a.length); //prints 2
console.log(a[0].length); //prints 3
console.log(a[0][0].length); //prints 4
console.log(a[0][0][0].length); //prints 5
︶ ̄淡然 2024-11-15 19:36:18

Fwiw,我发布了一个带有三维数组的对象 这里。在那个例子中,

objTeams.aaastrTeamsByLeagueCityYear["NFL"]["Detroit"][2012] == "Lions".

Fwiw, I posted an object with a three dimensional array here. In that example,

objTeams.aaastrTeamsByLeagueCityYear["NFL"]["Detroit"][2012] == "Lions".
青柠芒果 2024-11-15 19:36:18

非常简单的函数,生成任意维数的数组。指定每个维度的长度和内容,对我来说是 '' 通常

function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
  var args = arguments;
  function loop(array,dim) {
    for (var a = 0; a < args[dim + 1]; a++) {
      if (dims > dim) {
        array[a] = loop([],dim + 1);
      } else if (dims == dim) {
        array[a] = content;
      }
    }
    return array;
  }
  var thisArray = [];
  thisArray = loop(thisArray,1);
  return thisArray;
};

我经常使用这个函数,它节省了很多时间

Very simple function, generate an array with any number of dimensions. Specify length of each dimension and the content which for me is '' usually

function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
  var args = arguments;
  function loop(array,dim) {
    for (var a = 0; a < args[dim + 1]; a++) {
      if (dims > dim) {
        array[a] = loop([],dim + 1);
      } else if (dims == dim) {
        array[a] = content;
      }
    }
    return array;
  }
  var thisArray = [];
  thisArray = loop(thisArray,1);
  return thisArray;
};

I use this function very often, it saves a lot of time

月下伊人醉 2024-11-15 19:36:18

使用以下函数创建和初始化任意维度的数组

function ArrayND(initVal) 
{
    var args = arguments;
    var dims=arguments.length-1
    function ArrayCreate(cArr,dim)
    {
        if(dim<dims)
        {
            for(var i=0;i<args[1 + dim];i++)
            {
                if(dim==dims-1) cArr[i]=initVal
                else    cArr[i]=ArrayCreate([],dim+1)
            }
            return cArr
        }
    }
    return ArrayCreate([],0)
}

例如,要创建 2 行 3 列的数组,请像下面一样使用它

var a=ArrayND("Hello",2,3)

这将创建 require 数组并用“Hello”初始化所有值

类似地创建 4 维数组使用它喜欢

var a=ArrayND("Hello",2,3,4,5)

Use the following function to create and initialize Array of any dimension

function ArrayND(initVal) 
{
    var args = arguments;
    var dims=arguments.length-1
    function ArrayCreate(cArr,dim)
    {
        if(dim<dims)
        {
            for(var i=0;i<args[1 + dim];i++)
            {
                if(dim==dims-1) cArr[i]=initVal
                else    cArr[i]=ArrayCreate([],dim+1)
            }
            return cArr
        }
    }
    return ArrayCreate([],0)
}

For e.g to create an array of 2 rows and 3 columns use it like the following

var a=ArrayND("Hello",2,3)

This will create the require array and initialize all values with "Hello"

Similarly to create 4 dimensional array use it like

var a=ArrayND("Hello",2,3,4,5)
只有影子陪我不离不弃 2024-11-15 19:36:17
function make(dim, lvl, arr) {
  if (lvl === 1) return [];
  if (!lvl) lvl = dim;
  if (!arr) arr = [];
  for (var i = 0, l = dim; i < l; i += 1) {
    arr[i] = make(dim, lvl - 1, arr[i]);
  }
  return arr;
}

var myMultiArray = make(4);

更新:您可以在第一个参数中指定级别的深度,以及在第二个参数中指定级别的数量。例如:

var myMultiArray = make(64, 4);

这将允许您以这种格式设置和获取:

myMultiArray[X][X][X][X] = ....

但 X 必须始终小于 64。例如,您不能设置 myMultiArray[X][70][X][X],因为myMultiArray[X][70] 尚未定义

注意 - 运行 make(64, 4) 非常慢 - 您正在创建 64 ^ 4 个空数组元素(即16,777,216)。

更新 2: 您可以将最后一个值设置为任何数字或字符串。 IE。 myMultiArray[X][X][X][Y] 其中 X < 64 和 Y 可以是任何值。

算法也优化了,再试试吧。

function make(dim, lvl, arr) {
  if (lvl === 1) return [];
  if (!lvl) lvl = dim;
  if (!arr) arr = [];
  for (var i = 0, l = dim; i < l; i += 1) {
    arr[i] = make(dim, lvl - 1, arr[i]);
  }
  return arr;
}

var myMultiArray = make(4);

Update: you can specify how deep a level should be in the first parameter, and how many levels in the second. e.g.:

var myMultiArray = make(64, 4);

This will allow you to set and get in this format:

myMultiArray[X][X][X][X] = ....

But X must always be less than 64. You cannot set myMultiArray[X][70][X][X] for example, because myMultiArray[X][70] has not yet been defined

Note- running make(64, 4) is awfully slow - you are creating 64 ^ 4 empty array elements (i.e. 16,777,216).

Update 2: you can get away with the last value as any number or string. Ie. myMultiArray[X][X][X][Y] where X < 64 and Y can be anything.

The algorithm has been optimised as well, give it another go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文