2013-02-22 2 views
2

나는이 목적이 있습니다목록 객체에있는 모든 변수 이름은

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 객체 변수를 반복 할 수 있습니까?

+0

이것은 JSON 객체가 아닌 JavaScript 객체입니다. [JSON 개체] 같은 것은 없습니다. (http://benalman.com/news/2010/03/theres-no-suchthing-as-a-json/). –

+0

개체에 * 속성 *이 있지만 변수가 아닙니다. 당신이 찾고있는 것은 속성의 * 이름 *입니다. –

+0

링크 된 질문의 해답을 따르면 문자열 배열을 얻을 수 있습니다. 숫자로 변환하려면 http://stackoverflow.com/questions/2130454/javascript-to-convert-string-to-number를 참조하십시오. –

답변

2

대부분의 브라우저에는이 프로토 타입이 Object 프로토 타입에 내장되어 있습니다.

당신은 도움이

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

희망을 사용할 수 있습니다!

+0

굉장! 'for' 루프가 필요 없으므로이 솔루션을 더 좋아합니다. – SeinopSys

+0

이것은 문자열 배열을 반환합니다. – Mohsen

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

이것은 수동 솔루션입니다. 이런 문제에 대해서는 Underscore.js를 사용하는 것이 좋습니다. Underscore에는 좋은 _.keys 메서드가 있습니다.

+1

나는'.hasOwnProperty'도 여기에 놓았습니다. – Kos

+0

그냥 1) * 속성 * 이름의'[ToString]'때문에'[ ""94 ","21 ","36 "..] 2) 주문은 보장되지 않습니다. –

+0

@pst 순서가 정확하도록 새 배열을 만드는 방법이 있습니까? – SeinopSys

관련 문제