0

我找不到我的问题的解决方案。我可能会让事情变得更复杂。

这是数组:

var Statistics = {
"STAT 1 COLUMNS" : ["Date","Group Name","Product Name","Version","Version Date","Status","Total","Total L0","Total L1","Total L2","To be validated","Created","Updated"],
"STAT 2 TITLE" : ["12/12/2013","Led Zeppelin","roofies","V5.3","2013-08-13 ","ACCEPTED <br/>(2013-9-10)","774","334","3","437","20","57","102"],
"STAT 3 TITLE" : ["22/11/2014","Deep Purple","upper","V1","2006-01-01 "," ","3","1","0","2","1"," "," "],
...
}

我想通过指定索引来获取特定对象的对象名称(例如'STAT 1 COLUMNS'、'STAT 2 TITLE'、'STAT 3 TITLE'..)。

例如,请给我对象的名称('2') -> "STAT 3 TITLE"

你能帮帮我吗?

4

5 回答 5

1

尝试:

function givemepleasethenameoftheobject(index, data) {
  var i = 0;
  for ( var k in data ) {
    if ( index == i++ ) {
      return k;
    }
  }
}

var result = givemepleasethenameoftheobject(2, Statistics);
于 2013-09-12T08:52:36.943 回答
1

这应该可以实现您所需要的:

function getStatisticName(index)
{
    var count = 0;
    for(var i in Statistics)
    {
        if(count == index)
            return i;

        count++;
    }
}

看到这个jsFiddle

于 2013-09-12T08:53:16.727 回答
1

试试'Object.keys();' 功能。

Object.keys(Statistics); // ['STAT 1 COLUMNS', 'STAT 2 TITLE', 'STAT 3 TITLE'];
于 2013-09-12T08:55:25.090 回答
0

JavaScript 中不保证对象键的顺序,因此gimmeTheKey(Statistics, 2)保证返回"STAT 3 TITLE"

然而:

function gimmeTheKey( obj, idx ){
    return Object.keys( obj )[idx];
}
于 2013-09-12T08:55:40.437 回答
0

您可以像这样遍历对象的成员:

for (var key in Statistics) {
  console.log(key);
}

但是,您不能像这样通过索引可靠地访问它们。对象中的成员不能保证与您创建它们时保持相同的顺序,并且不同的浏览器实际上对成员的排序方式不同。

如果您想以可预测的方式通过索引访问成员名称,则需要获取所有名称然后对它们进行排序:

function givemepleasethenameoftheobject(index) {
  var keys = [];
  for (var key in Statistics) {
    keys.push(key);
  }
  keys.sort();
  return keys[index];
}

如果您不需要兼容旧版浏览器(例如 Internet Explorer 8),您可以使用以下Object.Keys方法

function givemepleasethenameoftheobject(index) {
  var keys = Object.keys(Statistics);
  keys.sort();
  return keys[index];
}
于 2013-09-12T08:56:27.923 回答