是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

当前回答

我非常喜欢的解决方案:

让我们定义一个空变量为空或未定义,或者如果它有长度,它为零,或者如果是一个对象,它没有键:

function isEmpty (value) {
  return (
    // null or undefined
    (value == null) ||

    // has length and it's zero
    (value.hasOwnProperty('length') && value.length === 0) ||

    // is an Object and has no keys
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

退货:

true:undefined,null,“”,[],{}false:true,false,1,0,-1,“foo”,[1,2,3],{foo:1}

其他回答

检查值是否未定义或为空的详细方法为:

return value === undefined || value === null;

您也可以使用==运算符,但这需要您了解所有规则:

return value == null; // also returns true if value is undefined

可以直接使用相等运算符

<script>
    var firstName;
    var lastName = null;
    /* Since null == undefined is true, the following statements will catch both null and undefined */
        if(firstName == null){
            alert('Variable "firstName" is undefined.');
        }    
        if(lastName == null){
           alert('Variable "lastName" is null.');
        }
</script>

demo@如何使用JavaScript确定变量是否未定义或为空

这将检查不确定嵌套的变量是否未定义

function Undef(str) 
{
  var ary = str.split('.');
  var w = window;
  for (i in ary) {
    try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
    catch(e) { return true; }
  }
  return false;
}

if (!Undef("google.translate.TranslateElement")) {

上面检查Google翻译函数TranslateElement是否存在。这相当于:

if (!(typeof google === "undefined" 
 || typeof google.translate === "undefined" 
 || typeof google.translate.TranslateElement === "undefined")) {

看看新的ECMAScript Nullish合并运算符

你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。

let x = foo ?? bar();

同样,上述代码与以下代码等效。

let x = (foo !== null && foo !== undefined) ? foo : bar();

我想这会让你的代码看起来更简单

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false