考虑:

var object = {
  foo: {},
  bar: {},
  baz: {}
}

我该怎么做:

var first = object[0];
console.log(first);

显然,这行不通,因为第一个索引名为foo, 不是0。

console.log(object['foo']);

工作,但我不知道它叫foo。它可以被命名为任何东西。我只想要第一个。


当前回答

如果对象的顺序很重要,你应该修改JSON模式以将对象存储在数组中:

[
    {"name":"foo", ...},
    {"name":"bar", ...},
    {"name":"baz", ...}
]

或者:

[
    ["foo", {}],
    ["bar", {}],
    ["baz", {}]
]

正如Ben Alpert所指出的,Javascript对象的属性是无序的,如果你期望它们按照在对象文字中指定的顺序枚举——没有“first”属性,那么你的代码就会被破坏。

其他回答

我的解决方案:

Object.prototype.__index = function(index)
{
    var i = -1;
    for (var key in this)
    {
        if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
            ++i;
        if (i >= index)
            return this[key];
    }
    return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

你可以这样做:

var object = {
    foo:{a:'first'},
    bar:{},
    baz:{}
}


function getAttributeByIndex(obj, index){
  var i = 0;
  for (var attr in obj){
    if (index === i){
      return obj[attr];
    }
    i++;
  }
  return null;
}


var first = getAttributeByIndex(object, 0); // returns the value of the
                                            // first (0 index) attribute
                                            // of the object ( {a:'first'} )

ES6

const [first] = Object.keys(obj)

如果对象的顺序很重要,你应该修改JSON模式以将对象存储在数组中:

[
    {"name":"foo", ...},
    {"name":"bar", ...},
    {"name":"baz", ...}
]

或者:

[
    ["foo", {}],
    ["bar", {}],
    ["baz", {}]
]

正如Ben Alpert所指出的,Javascript对象的属性是无序的,如果你期望它们按照在对象文字中指定的顺序枚举——没有“first”属性,那么你的代码就会被破坏。

如果你想要简洁的东西,试试:

for (first in obj) break;

alert(first);

包装成函数:

function first(obj) {
    for (var a in obj) return a;
}