考虑:

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

我该怎么做:

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

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

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

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


当前回答

我的解决方案:

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));

其他回答

ES6

const [first] = Object.keys(obj)

没有办法获得第一个元素,因为JavaScript中的“散列”(对象)具有无序属性。最好的方法是将键存储在数组中:

var keys = ["foo", "bar", "baz"];

然后使用它来获得正确的值:

object[keys[0]]

我的解决方案:

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'} )

它们并不是有序的,但是你可以这样做:

var first;
for (var i in obj) {
    if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
        first = obj[i];
        break;
    }
}

. hasownproperty()对于忽略原型对象很重要。