0

我正在尝试在 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".
4

2 回答 2

2

除非有任何理由你不能,否则我只会使用坐标作为索引,并在那里存储东西:

var coordinates = [];
var testCoord = [0,0,3,5];
coordinates[testCoord] = "Hello World";
console.log(coordinates[testCoord]);
于 2013-01-01T01:24:18.867 回答
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]));
于 2013-01-01T01:14:02.293 回答