列出对象中的所有变量名称

时间:2013-02-22 19:30:36

标签: javascript arrays

我有这个对象:

var sub = {
    0:  [""],
    21: ["Look, here, are three little stuff,","ready to sing for this crowd"],
    28: ["Listen up, 'cause here's our story","I'm gonna sing it very LOUUU..."],
    36: [""],
    45: ["VERY LOUUU..."],
    48: [""],
    61: ["When you're a younger stuff","and your stuff is very bare"],
    68: ["Feels like the sun will never come","when your stuff's not there"],
    74: ["So the three of us will fight the fight","there is nothing that we fear"],
    80: ["We'll have to figure out what we'll do next","till our stuff is here!"],
    87: ["We are the guys","on a quest to find out who we are"],
    94: ["And we will never stop the journey","not until we have our stuff"],
    101:[""],
    106:["(stuff...)"],
}
//I like stuff.

我希望将所有变量名称都放入数组中,如下所示:

variables == [0, 21, 28, 36, 45, 48, 61, 68, 74, 80, 87, 94, 101, 106, 109];

是否有内置函数,或者是否可以迭代JSON对象变量?

2 个答案:

答案 0 :(得分:5)

大多数浏览器都将此方法内置于Object原型中。

您可以使用

var variables = Object.keys(sub); //returns an array with all the object keys

希望有所帮助!

答案 1 :(得分:1)

var variables = [];
for (var i in sub) {
 if (sub.hasOwnProperty(i)){
  variables.push(+i);
 }
}

这是一个手动解决方案。我建议你使用Underscore.js来解决这个问题。在Underscore中有一个很好的_.keys方法。