我找不到我的问题的解决方案。我可能会让事情变得更复杂。
这是数组:
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'..)。
例如, givemepleasethenameoftheobject('2') - &gt; “STAT 3 TITLE”
你可以帮我一把吗?答案 0 :(得分:1)
尝试:
function givemepleasethenameoftheobject(index, data) {
var i = 0;
for ( var k in data ) {
if ( index == i++ ) {
return k;
}
}
}
var result = givemepleasethenameoftheobject(2, Statistics);
答案 1 :(得分:1)
这应该达到你的需要:
function getStatisticName(index)
{
var count = 0;
for(var i in Statistics)
{
if(count == index)
return i;
count++;
}
}
请参阅此jsFiddle
答案 2 :(得分:1)
尝试'Object.keys();'功能
Object.keys(Statistics); // ['STAT 1 COLUMNS', 'STAT 2 TITLE', 'STAT 3 TITLE'];
答案 3 :(得分:0)
JavaScript无法保证对象键顺序,因此gimmeTheKey(Statistics, 2)
无法保证返回"STAT 3 TITLE"
。
然而:
function gimmeTheKey( obj, idx ){
return Object.keys( obj )[idx];
}
答案 4 :(得分: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
method:
function givemepleasethenameoftheobject(index) {
var keys = Object.keys(Statistics);
keys.sort();
return keys[index];
}