简体   繁体   English

JavaScript - 控制二维动态数组

[英]JavaScript - control two-dimensional dynamic array

i want to init a two-dimensional dynamic array in javascript, it don't limit element (maybe) like 我想在javascript中初始化一个二维动态数组,它不限制元素(也许)就像

var dynamic = new Array ();
dynamic[] = new Array ();


after i want to add value to special array like 之后我想为特殊数组添加值

dynamic[id].push(2); // id = 3, dynamic[3][0] = 2
...
dynamic[id].push(3); // id = 3, dynamic[3][1] = 3
...
dynamic[id].push(5); // id = 5, dynamic[5][0] = 5

it's possible? 这是可能的? How can i do that, thanks 我怎么能这样做,谢谢

One thing you could do is something like this ( jsfiddle ): 你可以做的一件事是这样的( jsfiddle ):

var dynamic = [];

dynamic.push = function (id, value) {
    if (!this[id]) {
        this[id] = [];
    }

    this[id].push(value);
}

dynamic.push(3, 2);
dynamic.push(3, 3);
dynamic.push(5, 5);

Of course, this can be done even better, but it gets the point across. 当然,这可以做得更好,但它得到了重点。 Personally, I'd write a class for this. 就个人而言,我会为此写一堂课。

Edit : Also, keep in mind that this creates an array with a high potential of having a whole lot of undefined values, which needs to be taken care of when reading from it. 编辑 :另外,请记住,这会创建一个很可能具有大量undefined值的数组,从中读取时需要注意这些值。 Also, arrays with holes like this have bad performance (if this will be an issue -- for a few, even a few hundred, values, it won't matter). 此外,具有这样的孔的阵列具有不良性能(如果这将是一个问题 - 对于少数,甚至几百个值,它将无关紧要)。

Overwriting push might not be the best plan. 覆盖push可能不是最好的计划。 Adding another method/function would make it simpler to understand. 添加另一个方法/函数将使其更容易理解。 Someone reading push(1,3) might assume you're pushing 1 and 3 onto an array instead of 3 into item 1. 有人阅读push(1,3)可能会假设您将1和3推入数组而不是3进入第1项。

var dynamic = [];

dynamic.item = function(index) {
    if (!dynamic[index]) {
        dynamic[index] = [];
    }
    return dynamic[index];
}

this will allow you to do the following: 这将允许您执行以下操作:

dynamic.item(1).push(1)

if the "item" does not exist, it is created before its returned, and this allows you to use all array methods on both dimensions of your array. 如果“item”不存在,则在返回之前创建它,这允许您在数组的两个维度上使用所有数组方法。 (i beleive) (我相信)

You could also make this slightly more generic by adding it to the Array prototype which would let you use it on all arrays. 您还可以通过将其添加到Array原型来使其更加通用,这将允许您在所有阵列上使用它。

Array.prototype.item = function(index) {
    if (!this[index]) {
        this[index] = init;
    }
    return this[index];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM