Javascript:获取单个属性名称 [英] Javascript: Getting a Single Property Name
本文介绍了Javascript:获取单个属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出这样的对象:
{ name: "joe" }
我想获得值name。我知道我可以使用for构造来迭代对象中的属性,但是我将要处理的对象将始终只有一个键:值对,我不知道属性的名称。进一步说明:
I want to get the value "name". I know I can use the for construct to iterate over the properties in an object, but the objects I'll be dealing with will always have a single key:value pair, and I won't know the name of the property. To further illustrate:
var a = { age: 24 };
console.log(myFunc(a)) // Displays "age"
var b = { job: "cook" };
console.log(myFunc(b)) // Displays "job"
有没有无论如何要做到这一点而不迭代对象?我也想在纯Javascript中这样做。没有框架/库。
Is there anyway to do this without iterating over the object? Also I'd like to do this in pure Javascript. No frameworks/libs involved.
推荐答案
最好使用 .hasOwnProperty
确保您没有从Object原型返回属性:
It is good practice to use .hasOwnProperty
to ensure you aren't returning a property from the Object prototype:
function myFunc(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) return prop;
}
}
这篇关于Javascript:获取单个属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文