【问题标题】:List all variable names in a object [duplicate]列出对象中的所有变量名称[重复]
【发布时间】:2013-02-08 12:30:59
【问题描述】:

我有这个对象:

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 对象变量?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

大多数浏览器都在 Object 原型中内置了这个方法。

你可以使用

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

希望有帮助!

【讨论】:

  • 太棒了!我更喜欢这个解决方案,因为它不需要 for 循环。
  • 这将返回一个字符串数组
  • 感谢这对我有帮助!非常好的 awsner 而不是使用循环
【解决方案2】:
var variables = [];
for (var i in sub) {
 if (sub.hasOwnProperty(i)){
  variables.push(+i);
 }
}

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

【讨论】:

  • 我也想在这里写一个.hasOwnProperty
  • 请注意,这将 1) 由于 property 名称的 [ToString] 而返回 ["94", "21", "36", ..];和 2) 订单是保证的。
  • @pst 有没有办法以精确的顺​​序创建新数组?
  • @DJDavid98:不,对象属性没有特定的顺序。这就像一个哈希映射。
  • @FelixKling 我想我可以在上面使用.sort(),所以一切都会好的。
猜你喜欢
  • 2018-02-08
  • 2012-06-20
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多