是否可以创建无限维JavaScript数组?

时间:2013-01-01 01:09:16

标签: javascript

我正在尝试在JavaScript中创建(或模拟)无限维数组。从本质上讲,这将是一个数据结构,它将对象与整数列表(可以是任意长度)相关联。有没有一种有效的方法来存储这个数据结构中的每个元素?

function addElement(theObject, coordinates){
    //object is the object, and coordinates is the list of coordinates (any number of coordinates will be accepted, since it's infinite-dimensional)
}

function getObject(coordinates){
    //get the object that was previously assigned to this list of coordinates
}
addElement("Hello World", [0, 0, 3, 5]);
console.log(getObject([0, 0, 3, 5])); //this would print "Hello World".

2 个答案:

答案 0 :(得分:2)

除非有任何理由你不能,我只会将坐标用作索引,然后存储在那里:

var coordinates = [];
var testCoord = [0,0,3,5];
coordinates[testCoord] = "Hello World";
console.log(coordinates[testCoord]);

答案 1 :(得分:1)

绝对。只是循环:

(function() {
  var store = [];
  window.addElement = function(theObject,coordinates) {
    var t = store, l = coordinates.length, i;
    for(i=0; i<l-1; i++) {
      if( typeof t[coordinates[i]] !== "undefined" && !(t[coordinates[i]] instanceof Array))
        (function(old) {(t[coordinates[i]] = []).toString = function() {return old;};})(t[coordinates[i]]);
      t = t[coordinates[i]] = t[coordinates[i]] || [];
    }
    t[coordinates[i]] = theObject;
  }
  window.getObject = function(coordinates) {
    var t = store, l = coordinates.length, i;
    for(i=0; i<l-1; i++) {
      t = t[coordinates[i]];
      if( !(t instanceof Array)) throw new Error("Invalid coordinate");
    }
    return t[coordinates[i]];
  }
})();

addElement("Hello World",[0,0,3,5]);
console.log(getObject([0,0,3,5]));