Detecting an undefined object property

后端 未结 30 3655
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  轮回少年
    2020-11-21 05:42

    Going through the comments, for those who want to check both is it undefined or its value is null:

    //Just in JavaScript
    var s; // Undefined
    if (typeof s == "undefined" || s === null){
        alert('either it is undefined or value is null')
    }
    

    If you are using jQuery Library then jQuery.isEmptyObject() will suffice for both cases,

    var s; // Undefined
    jQuery.isEmptyObject(s); // Will return true;
    
    s = null; // Defined as null
    jQuery.isEmptyObject(s); // Will return true;
    
    //Usage
    if (jQuery.isEmptyObject(s)) {
        alert('Either variable:s is undefined or its value is null');
    } else {
         alert('variable:s has value ' + s);
    }
    
    s = 'something'; // Defined with some value
    jQuery.isEmptyObject(s); // Will return false;
    

提交回复
热议问题