如何检查javascript对象是否具有某个属性

时间:2012-04-02 14:46:41

标签: javascript object properties

假设我有一个像这样的javascript对象:

window.config
config.UI = {
        "opacity": {
            "_type": "float",
            "_tag": "input",
            "_value": "1",
            "_aka": "opacity",
            "_isShow":"1"
 }

如何判断“不透明度”对象是否具有名为“_test”的属性? 喜欢

var c=config.ui.opacity;
for(var i in c)
{
   //c[i]=="_test"?
}

如何判断是否已分配?

1 个答案:

答案 0 :(得分:14)

至少有三种方法可以做到这一点;您使用哪一个很大程度上取决于您,有时甚至是风格问题,尽管存在一些实质性差异:

if..in

您可以使用if..in

if ("_test" in config.UI.opacity)

...因为当在测试中使用时(与特殊的for..in循环相反),in测试以查看对象或其原​​型(或其原型的原型等)是否具有这个名字的财产。

hasOwnProperty

如果要从原型中排除属性(在您的示例中并不重要),可以使用hasOwnProperty,这是一个所有对象都从Object.prototype继承的函数:

if (config.UI.opacity.hasOwnProperty("_test"))

只需检索它并检查结果

最后,您可以检索属性(即使它不存在),并通过查看结果来决定如何处理结果;如果你向对象询问它没有的属性的价值,你将会回来undefined

var c = config.UI.opacity._test;
if (c) {
    // It's there and has a value other than undefined, "", 0, false, or null
}

var c = config.UI.opacity._test;
if (typeof c !== "undefined") {
    // It's there and has a value other than undefined
}

防守

如果config.UI可能根本没有opacity属性,那么你可以使所有这些更具防御性:

// The if..in version:
if (config.UI.opacity && "_test" in config.UI.opacity)

// The hasOwnProperty version
if (config.UI.opacity && config.UI.opacity.hasOwnProperty("_test"))

// The "just get it and then deal with the result" version:
var c = config.UI.opacity && config.UI.opacity._test;
if (c) { // Or if (typeof c !== "undefined") {

最后一个有效,因为与其他语言相比,&&运算符在JavaScript中特别强大;这是curiously-powerful || operator

的必然结果