javascript 获取第一个对象属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19138250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:31:33  来源:igfitidea点击:

Get value of first object property

javascriptobject

提问by HP.

I have a simple object that always has one key:valuelike var obj = {'mykey':'myvalue'}

我有一个简单的对象,它总是有一个key:valuevar obj = {'mykey':'myvalue'}

What is the fastest way and elegant way to get the value without really doing this?

在不真正这样做的情况下获得价值的最快方法和优雅方法是什么?

for (key in obj) {
  console.log(obj[key]);
  var value = obj[key];
}

Like can I access the value via index 0 or something?

就像我可以通过索引 0 或其他东西访问该值吗?

回答by thefourtheye

var value = obj[Object.keys(obj)[0]];

Object.keysis included in javascript 1.8.5. Please check the compatibility here http://kangax.github.io/es5-compat-table/#Object.keys

Object.keys包含在 javascript 1.8.5 中。请检查这里的兼容性http://kangax.github.io/es5-compat-table/#Object.keys

Edit:

编辑:

This is also defined in javascript 1.8.5 only.

这也仅在 javascript 1.8.5 中定义。

var value = obj[Object.getOwnPropertyNames(obj)[0]];

Reference:

参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Enumerating_all_properties_of_an_object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Enumrating_all_properties_of_an_object

回答by georg

function firstProp(obj) {
    for(var key in obj)
        return obj[key]
}