JavaScript:获取对象的第一个也是唯一的属性名称 [英] JavaScript: Get first and only property name of object
问题描述
如果我想枚举对象的属性并想要忽略原型,我会使用:
If I want to enumerate the properties of an object and want to ignore prototypes, I would use:
var instance = { ... };
for (var prop in instance) {
if (instance.hasOwnProperty(prop)) {
...
}
}
如果实例
只有一个属性,我想要什么获得该属性名称?有没有比这样做更简单的方法:
What if instance
only has one property, and I want to get that property name? Is there an easier way than doing this:
var instance = { id: "foobar" };
var singleMember = (function() {
for (var prop in instance) {
if (instance.hasOwnProperty(prop)) {
return prop;
}
}
})();
推荐答案
也许 Object.keys 可以为您服务。如果其长度返回1,则可以使用 yourObject [Objects.keys [0]]
来获取对象的唯一属性。 MDN-link还显示了一个自定义函数,用于没有键
方法 1 的环境。代码如下:
Maybe Object.keys can work for you. If its length returns 1, you can use yourObject[Objects.keys[0]]
to get the only property of the object. The MDN-link also shows a custom function for use in environments without the keys
method1. Code like this:
var obj = {foo:'bar'},
kyz = Object.keys(obj);
if (kyz.length === 1){
alert(obj[kyz[0]]); //=> 'bar'
} else {
/* loop through obj */
}
1 某些旧版浏览器不支持 Object.keys
。 MDN链接提供代码以使其在这些浏览器中工作。请参阅上述 MDN页中的标题兼容性
1 Some older browsers don't support Object.keys
. The MDN link supplies code to to make it work in these browsers too. See header Compatibility in the aforementioned MDN page
这篇关于JavaScript:获取对象的第一个也是唯一的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!