如何检查javascript对象是否具有特定属性

How to check if a javascript object has a certain property

本文关键字:是否 属性 对象 javascript 何检查 检查      更新时间:2023-09-26

假设我有一个如下的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"?
}

我如何发现它是否也被分配了?

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

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中特别强大;它是CCD_ 12算子奇异强大的推论。