首页 文章

如何确定变量是'undefined'还是'null'?

提问于
浏览
1711

如何确定变量是 undefined 还是 null ?我的代码如下:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  //DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

但是,如果我这样做,JavaScript解释器会暂停执行 .

24 回答

  • -3
    (null == undefined)  // true
    
    (null === undefined) // false
    

    因为===检查类型和值 . 两者的类型不同但 Value 相同 .

  • -1

    这是一个非常古老的问题,但我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:

    var EmpName = $("div#esd-names div#name").attr('class');
    
    // Undefined check
    if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
        // do something with your code
    }
    
    // Nullcheck
    if (Object.prototype.toString.call(EmpName) === '[object Null]'){
        // do something with your code
    }
    
  • -1

    我来写这个我自己的功能... javascript很奇怪

    几乎任何东西都可用 . (请注意,这也检查变量是否包含任何可用的值 . 但由于通常还需要此信息,我认为值得发布) . 请考虑留言 .

    function empty(v) {
            let type = typeof v;
            if(type === 'undefined') {
                return true;
            }
            if(type=== 'boolean') {
                return !v;
            }
            if(v === null) {
                return true;
            }
            if(v === undefined) {
                return true;
            }
            if(v instanceof Array) {
                if(v.length < 1) {
                    return true;
                }
            }
            else if(type === 'string') {
                if(v.length < 1) {
                    return true;
                }
                if(v==='0') {
                    return true;
                }
            }
            else if(type === 'object') {
                if(Object.keys(v).length < 1) {
                    return true;
                }
            }
            else if(type === 'number') {
                if(v===0) {
                    return true;
                }
            }
            return false;
        }
    

    打字稿兼容 .

    编辑 . 这个函数应该像PHPs empty() function完全一样(见 RETURN VALUES

    undefinednullfalse00.0"0" {}[] 视为空 .

    "0.0"NaN" "true 被视为非空 .

  • 2350

    调用typeof null将返回值“object”,因为特殊值null被视为空对象引用 . 通过版本5的Safari和通过版本7的Chrome有一个怪癖,其中正则表达式上的调用typeof返回“function”,而所有其他浏览器返回“object” .

  • 964
    if (variable == null) {
        // Do stuff, will only match null or undefined, this won't match false
    }
    
  • 171

    jQuery check元素不为null

    var dvElement = $('#dvElement');
    
    if (dvElement.length  > 0) {
        //do something
    }
    else{
        //else do something else
    }
    
  • 3

    我在chrome控制台上运行此测试,使用(void 0)你可以检查undefined

    var c;
    undefined
    if(c === void 0)alert();
    // output =  undefined
    var c = 1;
    // output =  undefined
    if(c === void 0)alert();
    // output =   undefined
    // check c value  c
    // output =  1
    if(c === void 0)alert();
    // output =  undefined
    c = undefined;
    // output =  undefined
    if(c === void 0)alert();
    // output =   undefined
    
  • 4

    jQuery attr() 函数返回空字符串或实际值(从不 nullundefined ) . 它返回 undefined 的唯一时间是你的选择器没有返回任何元素 .

    所以你可能想测试一个空字符串 . 或者,由于空字符串(null和undefined)为false-y,因此您可以这样做:

    if (!EmpName) { //do something }
    
  • -1

    if(x==null) 在javascript中是个坏主意,用 "==" 判断可能会导致意外类型强制,并且无法通过咖啡脚本读取 never use "==" or "!=" in condition judgment!

    if(x) 会更好 . 但是因为 0 and "" ,它将被视为 false ,与 "!= null" 不相等的方法是 true .

    https://www.w3schools.com/js/js_best_practices.asp

  • 9

    您可以使用abstract equality operator的质量来执行此操作:

    if (variable == null){
        // your code here.
    }
    

    因为 null == undefined 为真,所以上面的代码将同时捕获 nullundefined .

  • 81

    最好的办法:

    if(typeof variable==='undefined' || variable===null) {
    
    /* do your stuff */
    }
    
  • -1

    您可以通过简单地使用typeof来检查值是未定义还是null:

    if(typeof value == 'undefined'){
    
  • 22

    结合上述答案,似乎最完整的答案是:

    if( typeof variable === 'undefined' || variable === null ){
        // Do stuff
    }
    

    这适用于任何未声明或声明的变量,并显式设置为null或undefined . 对于具有实际非空值的任何声明变量,布尔表达式应该求值为false .

  • 0

    要测试变量是否为null或未定义,请使用以下代码 .

    if(sVal === '' || sVal === null ||typeof sVal === 'undefined'){
        console.log('variable is undefined or null');
        }
    
  • 3

    我看到原帖是使用JQuery . 所以我通过JQuery添加过去使用过的东西 . 通常当我执行这样的检查时,我不一定要为此目的检查值为null或undefined . 更像是“那里有 Value 所以我可以对它采取行动 . ”因此,我使用以下内容 . 我没有尝试过每种类型,但我知道它适用于null和undefined . 此外,对象和数组(这些的空版本将返回true) . 此外,当然如果变量不存在,你将得到一个例外,但老实说,我会不惜一切代价避免这种情况 . 所以我同意Aerovistae . 我想在我的代码中知道这一点,不想只是跳过它 .

    if ($.trim(value) != '') {
       //Do Something
    }
    
  • 7

    同时捕获 nullundefined 的标准方法是:

    if (variable == null) {
         // do something 
    }
    
    • 这是100%相当于更明确但不简洁:
    if (variable === undefined || variable === null) {
         // do something 
    }
    

    在编写专业JS时,理解type equality and the behavior of == vs ===是理所当然的 . 因此我们使用 == 并仅与 null 进行比较 .


    再次编辑

    建议使用 typeof 的评论完全错误 . 是的,如果变量不存在,我上面的解决方案将导致ReferenceError . 这是件好事 . 这个ReferenceError是可取的:它可以帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样 .

    You should not have any references to undeclared variables in your code.

  • 2
    if (typeof EmpName != 'undefined' && EmpName) {
    

    如果值不是,则评估为真:

    • null

    • undefined

    • NaN

    • empty string ("")

    • 0

    • false

  • 1

    使用以下解决方案:

    const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
    const isDeepEqual = (a, b) => getType(a) === getType(b);
    
    console.log(isDeepEqual(1, 1)); // true
    console.log(isDeepEqual(null, null)); // true
    console.log(isDeepEqual([], [])); // true
    console.log(isDeepEqual(1, "1")); // false
    etc...
    

    我能够检查以下内容:

    • null

    • undefined

    • NaN

    • string(“”)

    • 0

  • 179

    如果要检查的变量是全局变量,请执行

    if (window.yourVarName) {
        // Your code here
    }
    

    即使 yourVarName 变量不存在,这种检查方式也不会抛出错误 .

    示例:我想知道我的浏览器是否支持History API

    if (window.history) {
        history.back();
    }
    

    这是如何工作的:

    window 是一个对象,它将所有全局变量保存为其属性,并且在JavaScript中尝试访问不存在的对象属性是合法的 . 如果 history 不存在则 window.history 返回 undefined . undefined 是假的,因此 if(undefined){} 块中的代码不会运行 .

  • 1
    var x;
    if (x === undefined) {
        alert ("only declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("not even declared.")
    };
    

    您只能使用第二个:因为它将检查定义和声明

  • 0

    在某些情况下,可以更改 undefined 的值 . 虽然这些通常很少见,但有时最好避免实际使用 undefined 值 .

    结果,因为它写得更快,我已经习惯使用 undefined 的快捷方式来查看空数组的第一个值 . 该值保证为原始值 undefined ,可以使用 [][0] 进行访问 .

    此检查将用于查找 undefinednull .

    这是一个例子:

    (function(undefined){
        var foo = { baz: null };
        console.log(foo.bar === undefined); //false
        console.log(foo.bar == [][0]); //true
        console.log(foo.baz == [][0]); //true
    }(50))
    
  • -4
    var i;
    
    if(i === null || typeof i === 'undefined'){
    console.log(i,'i is undefined or null')
    }else{
    console.log(i,'i has some value')
    }
    
  • 6

    我刚遇到这个问题,即检查对象是否为空 .
    我只是用这个:

    if (object) { Somecode}
    

    if (document.getElementById("enterJob")) 
      document.getElementById("enterJob").className += ' current';
    
  • -1

    由于您使用的是 jQuery ,因此可以使用单个函数确定变量是未定义还是其值为null .

    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;
    

相关问题