按索引访问非数字对象属性? [英] Access non-numeric Object properties by index?

查看:31
本文介绍了按索引访问非数字对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个这样的数组:

If I have an array like this:

var arr = ['one','two','three'];

我可以通过这样做访问不同的部分:

I can access different parts by doing this:

console.log(arr[1]);

如何按顺序而不是按键访问对象属性?

How can I access object properties by their order rather than by key?

示例:

var obj = {
    'something' : 'awesome',
    'evenmore'  : 'crazy'
},
jbo = {
    'evenmore'  : 'crazy',
    'something' : 'awesome'
};

如何获取每个对象的第一个属性——obj 中的something"和 jbo 中的evenmore"——而不显式使用属性名称?

How would I get the first property for each object–"something" from obj and "evenmore" from jbo–without explicitly using the property name?

现在,你们中的一些人似乎认为我在追求类似的东西:

Now, a few of you seem to think I'm after something like:

console.log(obj['something']);

事实并非如此,我特别希望以索引为目标,就像第一个示例一样 - 如果可能的话.

This is not the case, I'm specifically looking to target the index, just like the first example - if it's possible.

推荐答案

我特别希望以索引为目标,就像第一个示例一样 - 如果可能的话."

不,这不可能.

最接近的是获取对象键的数组,然后使用它:

The closest you can get is to get an Array of the object's keys, and use that:

var keys = Object.keys( obj );

...但不能保证密钥会按照您定义的顺序返回.所以它最终可能看起来像:

...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:

keys[ 0 ];  // 'evenmore'
keys[ 1 ];  // 'something'

这篇关于按索引访问非数字对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆