在JavaScript中是否有标准函数来检查null、undefined或空变量?

3053

是否有一种通用的JavaScript函数,可以检查变量是否具有值,并确保它不是undefinednull?我有这段代码,但我不确定它是否涵盖了所有情况:

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

6
可能是如何在JavaScript中检查空字符串?的重复问题。 - Dour High Arch
191
提示,永远不要写成(truthy statement) ? true : false;。直接写成(truthy statement);即可。 - David Baucum
11
@GeorgeJempty并不是重复的,因为另一个答案特别提到了“字符串”,而这个问题是关于“变量”的。请注意,此处仅进行翻译,不涉及任何解释或其他内容。 - Madbreaks
4
对于这个问题的任何正确答案完全依赖于你如何定义“空白”。 - Madbreaks
7
@Jay,这并不会影响您代码的执行,只是过于冗长。就像您不会说,“Is are you hungry is true?” 而是 “Are you hungry?”所以在代码中只需使用 if (hungry) … 而不是 if (hungry === true) …。就像所有编码风格一样,这只是个人审美问题。更具体地说,对于 OP 提供的例子,他更冗长地表达了“如果它为真,则为真,如果不为真,则为假”,但如果它为真,则已经是真的。如果它为假,则已经是假的。这相当于说:“如果你饿了,那么你就饿了,如果不饿,那么你就不饿。” - David Baucum
显示剩余11条评论
47个回答

2

这是我检查数据是否为空的解决方案。

const _isEmpty = (data) => {
  return (
    // this way we can also check for undefined values. null==undefined is true
    data == null ||
    data == "" ||
    (Array.isArray(data) && data.length === 0) ||
    // we want {} to be false. we cannot use !! because !!{} turns to be true
    // !!{}=true and !!{name:"yilmaz"}=true. !! does not work ofr objects
    (data.constructor === Object && Object.keys(data).length === 0)

  );
};

2

仅在值为undefinednull时返回false

return value ?? false


2
不是这样的:false ?? false === false - Pi Delport
是的,这个建议对于“false”输入也会返回“false”… - kli
1
要明确的是,这个答案是不正确的,因为 !(0 ?? false) === true - bnieland

2
function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

它还将检查空格(' ')以及以下内容:

  • null,undefined,NaN,empty,string(""),0,false

1

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

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")) {

上述代码检查谷歌翻译功能TranslateElement是否存在。这相当于:
if (!(typeof google === "undefined" 
 || typeof google.translate === "undefined" 
 || typeof google.translate.TranslateElement === "undefined")) {

1
我认为这会让你的代码看起来更简单。
要检查变量是否为undefinednull
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

检查变量是否不是 undefinednull

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

1

尝试使用Boolean()isNaN()(对于数字类型)检查变量是否有值。

function isEmpty(val) {
  return typeof val === 'number' ? isNaN(val) : !Boolean(val);
}

var emptyVals = [undefined, null, false, NaN, ''];
emptyVals.forEach(v => console.log(isEmpty(v)));


1
大多数现有答案都不能满足我的需求,如果将函数分配给变量或返回NaN,则大多数答案会返回空值。Pascal的答案不错。
这是我的实现,请测试并让我知道您是否发现了任何问题。您可以在此处查看我如何测试此函数here
function isEmpty(value) {
  return (
    // Null or undefined.
    (value == null) ||
    // Check if a Set() or Map() is empty
    (value.size === 0) ||
    // NaN - The only JavaScript value that is unequal to itself.
    (value !== value) ||
    // Length is zero && it's not a function.
    (value.length === 0 && typeof value !== "function") ||
    // Is an Object && has no keys.
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

返回:

  • true: undefined, null, "", [], {}, NaN, new Set(), //
  • false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }, function () {}

0

您可以直接使用等号运算符

<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>

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


0
try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

我认为使用try catch可以避免任何空值检查错误,在Angular或JavaScript中只需捕获空异常并进行处理。


1
包含代码的解释以及为什么它能回答问题可能会更有帮助。仅发布代码有时可能不够清晰。 - Harsha Biyani
你应该添加一份解释来证明你的答案。 - Gufran Hasan
我尝试使用Angular编码,并参考了这个问题中的一些解决方案,但我发现在这种情况下,try catch是一种安全的处理方式:D - nobjta_9x_tq

0

我认为使用 ? 运算符会更加简洁。

var ? function_if_exists() : function_if_doesnt_exist();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接