这真的是获取单个属性对象值的最短方法吗? [英] Is this really the shortest way to get the value of a single property object?

查看:54
本文介绍了这真的是获取单个属性对象值的最短方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只有一个属性的对象,我不知道它的名字.

I have an object with a single property, which name I do not know.

使用纯javascript,下面真的是获取这个属性值的最短方法吗?

Using pure javascript, is the following really the shortest way to get the value of this property?

obj[Object.keys(obj)[0]]

看起来很多.有没有更好的选择?再次不使用任何 JS 库.

Seems like an awful lot. Is there any better alternative? Again not using any JS libraries.

推荐答案

在你描述的场景中(有一个你不知道的一个键的对象),是的,这是最短的访问方式.

In your described scenario (having an object with one key, which you don't know), yes, that is the shortest way of accessing it.

顺便说一下,鉴于当时的情况,我感觉并不多.请注意,这仅适用于支持 ES5 的浏览器.没有 ES5,它变得更多:

I don't feel its a lot, given the circumstances by the way. Be aware tho that this will only work on ES5 enabled browsers. Without ES5, it will become a lot more:

var propName;
for( var prop in obj ) {
    if( obj.hasOwnProperty( prop ) ) {
        propName = prop;
        // break;
    }
}

obj[propName]; 

这篇关于这真的是获取单个属性对象值的最短方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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