繁体   English   中英

如何检查深层属性的存在

[英]How to check existence of a deep property

以下代码是否有更好的解决方案:

 if (response && response.responseJSON && response.responseJSON.message) {
        //code
}

你在做什么很好。 看起来有些丑陋,但是可以清楚地知道发生了什么。 如果您确实希望这样做,则可以将完整表达式放在try-catch块中,但这将是较差的做法,并且更难于阅读/维护。

我想您想要像Groovy的“ 安全导航操作员 ”这样的东西,所以您可以这样做:

if (response?.responseJSON?.message)

但是Javascript没有这样的功能。

您可以随时使用辅助函数:

Object.prototype.deepExist = function(attPath){
    var o = this,
        path = attPath.split(".");

    for (var i=0; i<path.length; i++){
        o = o[path[i]];
        if (!o) {
            return false;   
        }
    }
    return true;
}

用法:

if (response.deepExist("responseJSON.message")){
    //code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM