如何创建对象列表的javascript数组?

时间:2014-04-15 23:15:54

标签: javascript arrays

我需要创建一个列表字典。这可能在Javascript中吗?我正在寻找能让我为特征/子特征对添加对象并迭代特征/子特征集合的东西。我的功能/子功能数据是一系列整数对:

[1,2], [1,3], [1,23], [2,4], [2, 12], ....

其中第一个数字是特征索引,第二个数字是子特征索引。这些对中的每一对都可以具有对象列表。我想按特征索引迭代列表,按对象迭代它们。像

这样的东西
forEach( item where feature index == someIndex, function(foo) {
     forEach (item[someindex, foo.index] , function(bar) {
             display bar.prop1, bar.prop2, ....

我将进行数据库调用并将结果作为项添加到此结构中。

这个结构模仿我在.Net中放在一起的东西,使用一个字典,它使用元组作为键,对象列表作为值。宣言是:

Dictionary <tuple[], list<myobject>>

谢谢,

杰里

3 个答案:

答案 0 :(得分:1)

一个简单的解决方案就是嵌套数组,所以像

var arr = [[2,3]];

因此,每次推送到数组时,只需添加一个新数组作为条目

arr.push([1,2]);

然后我会保留一个单独的数组来存储实际的功能/子功能,并直接使用该数字访问它们。如下所示:

arr.forEach(function(item) {
    if (item[0] == someIndex) {
        subfeatures[item[1]].forEach(function(feature) {
            // Do something with the feature
        });
    }
});

希望能让你朝着正确的方向前进!

答案 1 :(得分:0)

此示例可能比您需要的多一点。但也许你会发现好处。

//Object representing a Feature
function Feature(featureID, subFeatureID, list)
{
  this.featureID = featureID;
  this.subFeatureID = subFeatureID;
  this.list = list;
}

//Object to hold features
function FeatureCollection()
{
    this._collection = new Array();
}

//Augment the FeatureCollection prototype


FeatureCollection.prototype.add = function(feature)
{
    this._collection.push(feature);
};

FeatureCollection.prototype.foreach = function(someIndex, listFunction)
{
  //For each feature set, loop within the collection
  //until the someIndex is found
  for(var i=0,length=this._collection.length;i<length;i++)
  {
      //Store a local scoped variable of the feature
      var feature = this._collection[i];
      if(feature.featureID === someIndex)
      {
        //For each of the object within the feature's list
        //invoke a function passing feature as 'this'
        for(var x=0,xlength=feature.list.length; x<xlength;x++)
        {
          listFunction.call(feature, feature.list[x]);
        }
        break;        
      }
  }

}

//Create a feature collection
var featureCollection = new FeatureCollection();

//Create a new feature
var testFeature = new Feature(1,2,["hello","world"])

//Add the feature to the collection
featureCollection.add(testFeature)

//Iterate the collection invoking the provided anonymous
//function if the index passed matches
featureCollection.foreach(1, function(listItem)
{
  console.log("FeatureID: " + this.featureID + " ListItemValue:" + listItem)
});

http://jsbin.com/firiquni/1/edit

答案 2 :(得分:0)

如果您不需要任何花哨的东西,并且您知道两个阵列的限制,那么您可以做一些技巧。

有些人可能认为它很苛刻,有些人会认为它很优雅。

您可以使用对象和哈希,而不是使用数组。将两个索引转换为字符串值以用作哈希键。

var myVals = {};
myVals["1,4"] = "Hi";
myVals["9,5"] = "There";

for (var i = 0; i < 10; i++) {
  for (j = 0; j < 10; j++) {
    var key = i + "," + j;
    var val = myVals[key];
    if (val) {
      // do something
    }
}
相关问题