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
Get value of first object property
提问by HP.
I have a simple object that always has one key:value
like var obj = {'mykey':'myvalue'}
我有一个简单的对象,它总是有一个key:value
像var 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.keys
is 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:
参考:
回答by georg
function firstProp(obj) {
for(var key in obj)
return obj[key]
}