2013-04-04 55 views
0

我有看起来像这样的对象。Javascript - 对象,for循环从2开始

foo = { 
    0 : { 
     'bar' : 'baz', 
     'qux' : 'quux', 
     'this' : { 'hello' : 'yes' } // this is the object I want to extract 
    } 
    1 : { 
     'bar' : 'baz', 
     'qux' : 'quux', 
     'this' : { 'hello' : 'yes' } // extract 
    } 
    2 : { 
     'bar' : 'baz', 
     'qux' : 'quux', 
     'this' : { 'hello' : 'yes' }, // extract 
     'that' : { 'hello' : 'no' } // extract 
    } 
} 

用了这样的循环,我得到遍历每个对象:

for(var i in foo){ 
    ... 
} 

的问题是,我只是想拉从第三和更大的子对象中的数据比(”这')从每个对象。

+4

对象属性没有排序。改用数组。 – VisioN 2013-04-04 09:12:54

+0

对象是无序的。没有真正的“第一”或“第二”键值对的概念。你只是试图让所有发生的值都是对象的键? – Blender 2013-04-04 09:13:15

+0

如果我总是知道他们会按这个顺序来? – Philip 2013-04-04 09:13:59

回答

2

在ECMAscript中没有指定对象键的指定顺序。如果您有索引的键名,那么您确实应该使用Javascript Array

如果你需要有一个普通的对象,你可能想使用Object.keys()一起Array.prototype.forEach.sort(),像

Object.keys(foo).sort().forEach(function(i) { 
}); 

如果你不能依靠ES5,你别无选择但要手动完成这项工作。

var keys = [ ]; 

for(var key in foo) { 
    if(foo.hasOwnProperty(key)) { 
     keys.push(key); 
    } 
} 

keys.sort(); 

for(var i = 0, len = keys.length; i < len; i++) { 
} 

但是,你真的应该只使用一个阵列摆在首位,所以你可以跳过肮脏的工作。

+0

问题是我不能使用Object.keys与IE。 – Philip 2013-04-04 09:15:33

+0

然后使用polyfill。 – elclanrs 2013-04-04 09:16:00

+0

感谢您的解决方案,我认为我会做一个数组。 =) – Philip 2013-04-04 09:19:48