如何检查对象是否具有属性javascript? [英] How to check if object has property javascript?

查看:45
本文介绍了如何检查对象是否具有属性javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

      function ddd(object) {
        if (object.id !== null) {
            //do something...
        } 
    }

但是我得到这个错误:

Cannot read property 'id' of null

如何检查对象是否具有属性并检查属性值?

How can I check if object has property and to check the property value??

推荐答案

hasOwnProperty 是您要查找的方法

if (object.hasOwnProperty('id')) {
    // do stuff
}

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

作为替代方案,您可以执行以下操作:

As an alternative, you can do something like:

if (typeof object.id !== 'undefined') {
    // note that the variable is defined, but could still be 'null'
}

在这种特殊情况下,您看到的错误表明 object 为null,而不是 id ,因此请警惕这种情况.

In this particular case, the error you're seeing suggests that object is null, not id so be wary of that scenario.

为了测试类似的各种东西的笨拙的深层嵌套属性,我使用了 brototype .

For testing awkward deeply nested properties of various things like this, I use brototype.

这篇关于如何检查对象是否具有属性javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆