下面创建一个对象,并为对象添加一些属性:
var user = {}; if(!user['Jason'']) { user['Jason''] = []; } user['Jason'']['grade''] = 3; user['Jason'']['isChinese''] = 1; if(!user['arthinking'']) { user['arthinking''] = []; } user['Jason'']['grade''] = 4; user['Jason'']['isChinese''] = 1;
我们获取user.length时发现,它是undefined的,我们只能通过for in循环获取对象的属性:
for(var key in user){ console.log('key: ', key); }
可以发现,循环输出的属性并不是按照创建的属性进行排列的。
如果我们需要按照一定的顺序输出属性,也可以先在一个数组中保存所有的key值,再将数组排序,最后循环这个key数组,通过key获取对象中的属性即可:
var user = {}; if(!user['Jason']) { user['Jason'] = []; } user['Jason']['grade'] = 3; user['Jason']['level'] = 1; if(!user['arthinking']) { user['arthinking'] = []; } user['arthinking']['grade'] = 4; user['arthinking']['level'] = 1; console.log(user); for(var key in user){ console.log('key: ', key); } var keys = []; for(var key in user){ keys.push(key); } keys = keys.sort(); for(var i=0; ivar key = keys[i]; console.log(user[key]['grade']); }