如何在Javascript中访问对象的第一个属性?

本文探讨了在JavaScript中如何优雅地访问对象的第一个属性,即使不知道属性名。文中提到可以使用`Object.keys`方法,但可能不适用于旧版IE浏览器,并提供了一种更简洁的解决方案。还讨论了依赖于JavaScript VM实现的对象属性存储顺序问题。
摘要由CSDN通过智能技术生成

本文翻译自:How to access the first property of an object in Javascript?

Is there an elegant way to access the first property of an object... 是否有一种优雅的方式来访问对象的第一个属性...

  1. where you don't know the name of your properties 你不知道你的房产名称的地方
  2. without using a loop like for .. in or jQuery's $.each 不使用像for .. in或者jQuery的$.each

For example, I need to access foo1 object without knowing the name of foo1: 例如,我需要在不知道foo1名称的情况下访问foo1对象:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

#1楼

参考:https://stackoom.com/question/47n9/如何在Javascript中访问对象的第一个属性


#2楼

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Using this you can access also other properties by indexes. 使用此方法,您还可以通过索引访问其他属性。 Be aware tho! 请注意! Object.keys return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this. 根据ECMAScript不保证Object.keys返回顺序,但是非正式地是所有主要浏览器实现,请阅读https://stackoverflow.com/a/23202095以获取详细信息。


#3楼

I don't recommend you to use Object.keys since its not supported in old IE versions. 我不建议您使用Object.keys,因为它在旧的IE版本中不受支持。 But if you really need that, you could use the code above to guarantee the back compatibility: 但是如果你真的需要它,你可以使用上面的代码来保证后面的兼容性:

if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;

return function (obj) {
  if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

  var result = [];

  for (var prop in obj) {
    if (hasOwnProperty.call(obj, prop)) result.push(prop);
  }

  if (hasDontEnumBug) {
    for (var i=0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
    }
  }
  return result;
}})()};

Feature Firefox (Gecko)4 (2.0) Chrome 5 Internet Explorer 9 Opera 12 Safari 5 功能Firefox(Gecko)4(2.0)Chrome 5 Internet Explorer 9 Opera 12 Safari 5

More info: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys 更多信息: https//developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys

But if you only need the first one, we could arrange a shorter solution like: 但如果你只需要第一个,我们可以安排一个更短的解决方案,如:

var data = {"key1":"123","key2":"456"};
var first = {};
for(key in data){
    if(data.hasOwnProperty(key)){
        first.key = key;
        first.content =  data[key];
        break;
    }
}
console.log(first); // {key:"key",content:"123"}

#4楼

一个规则版本:

var val = example[function() { for (var k in example) return k }()];

#5楼

你也可以做Object.values(example)[0]


#6楼

Solution with lodash library: 使用lodash库的解决方案:

_.find(example) // => {name: "foo1"}

but there is no guarantee of the object properties internal storage order because it depends on javascript VM implementation. 但是不能保证对象属性内部存储顺序,因为它依赖于javascript VM实现。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值