2452

如何确定变量是undefinednull

我的代码如下:

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

但如果我这样做,JavaScript 解释器会停止执行。

4

33 回答 33

3287

您可以使用抽象相等运算符的特性来执行此操作:

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

因为null == undefined是真的,上面的代码会同时捕获nullundefined

于 2010-04-15T18:14:35.087 回答
1251

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

if (variable == null) {
     // do something 
}

-- 这 100% 等同于更明确但不太简洁的:

if (variable === undefined || variable === null) {
     // do something 
}

在编写专业的 JS 时,理所当然地认为类型平等和=====理解vs的行为是理所当然的。因此,我们使用==并且仅与 比较null


再次编辑

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

您不应在代码中引用任何未声明的变量。

于 2014-01-22T03:01:31.737 回答
275

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

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

这应该适用于任何未声明或已声明并显式设置为 null 或未定义的变量。对于具有实际非空值的任何已声明变量,布尔表达式的计算结果应为 false。

于 2013-10-11T17:02:17.463 回答
194
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
于 2010-04-15T18:25:33.427 回答
104
if (typeof EmpName != 'undefined' && EmpName) {

如果 value 不是,将评估为 true:

  • 空值

  • 不明确的

  • 空字符串 ("")

  • 0

  • 错误的

于 2015-05-07T07:24:01.147 回答
43

可能最短的方法是:

if(EmpName == null) { /* DO SOMETHING */ };

这是证据:

function check(EmpName) {
  if(EmpName == null) { return true; };
  return false;
}

var log = (t,a) => console.log(`${t} -> ${check(a)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" 

这里有更多关于==(来源在这里

在此处输入图像描述

奖金:原因=====(查看agc 答案)更清楚

在此处输入图像描述

于 2020-01-07T15:47:22.480 回答
33

jQueryattr()函数返回一个空白字符串或实际值(从不nullundefined)。它返回的唯一时间undefined是您的选择器没有返回任何元素。

因此,您可能希望针对空白字符串进行测试。或者,由于空白字符串、null 和 undefined 是 false-y,您可以这样做:

if (!EmpName) { //do something }
于 2010-04-15T18:20:06.900 回答
26

编辑答案:在我看来,你不应该使用我下面的旧答案中的功能。相反,您可能应该知道变量的类型并直接使用根据检查(例如,想知道数组是否为空?只是做if(arr.length===0){}等)。这个答案甚至没有回答 OP 的问题。


我来为此编写自己的函数。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;
}

TypeScript 兼容。


该函数应该与 PHP 的函数完全相同(请参阅 参考资料)empty()RETURN VALUES

认为undefined, null, false, 0, 0.0, "0" {},[]为空。

"0.0", NaN, " ",true被认为是非空的。

于 2015-10-24T15:14:21.323 回答
23

最短和最简单的:

if(!EmpName ){
 // DO SOMETHING
}

如果 EmpName 是,这将评估 true:

  • 空值
  • 不明确的
  • 空的
  • 细绳 (””)
  • 0
  • 错误的
于 2019-08-15T10:15:50.407 回答
15

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

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

即使yourVarName变量不存在,这种检查方式也不会引发错误。

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

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

这是如何工作的:

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

于 2014-02-10T16:30:11.163 回答
13

JavaScript中,据我所知,我们可以检查undefinednull变量,如下所示。

if (variable === undefined){
}

if (variable === null){
}

if (variable === ''){
}

检查所有条件:

if(variable === undefined || variable === null || variable === ''){
}
于 2019-11-07T04:39:50.223 回答
11

由于您使用的是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;
于 2014-07-08T08:00:58.857 回答
10

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

if (object) {
    // Your code
}

例如:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}
于 2013-10-15T16:44:32.757 回答
8

您可以简单地使用以下方法(我知道有更短的方法可以做到这一点,但这可能更容易直观地观察,至少对于其他查看代码的人来说)。

if (x === null || x === undefined) {
 // Add your response code here, etc.
}

来源:https ://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/

于 2019-07-29T14:25:56.107 回答
6

jQuery 检查元素不为空:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}
于 2015-03-04T17:10:20.563 回答
5

最简单的检查方法是:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
于 2019-05-28T06:30:19.837 回答
4

随着最新的 javascript 更改,您可以使用新的逻辑运算符??=来检查左操作数是否为nullundefined,如果是,则分配右操作数的值。

所以,

if(EmpName == null){  // if Variable EmpName null or undefined
  EmpName = 'some value';
};

相当于:

EmpName ??= 'some value';
于 2021-05-25T00:48:13.213 回答
3

要测试变量是否为空或未定义,我使用以下代码。

    if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
      console.log('variable is undefined or null');
    }
于 2016-03-03T04:57:23.650 回答
3

我在 Chrome 控制台中运行此测试。使用 (void 0) 您可以检查未定义:

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
于 2016-05-18T20:10:58.680 回答
3

使用以下解决方案:

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

我可以检查以下内容:

  • 空值
  • 不明确的
  • 空的
  • 细绳 (””)
  • 0
  • 错误的
于 2017-12-12T10:29:54.013 回答
2
(null == undefined)  // true

(null === undefined) // false

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

于 2018-05-27T11:19:18.867 回答
2

让我们看看这个,

  1.  

    let apple; // Only declare the variable as apple
    alert(apple); // undefined
    

    在上面,变量只被声明为apple. 在这种情况下,如果我们调用方法alert,它将显示未定义。

  2.  

       let apple = null; /* Declare the variable as apple and initialized but the value is null */
       alert(apple); // null
    

在第二个中它显示 null,因为applevalue 变量为 null。

所以你可以检查一个值是未定义的还是空的。

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}
于 2020-02-11T05:47:24.747 回答
2

检查应该可以解决问题并以foo == null最短的方式解决“未定义或空”的情况。(不考虑“未声明 foo”的情况。)但是习惯了 3 个等于(作为最佳实践)的人可能不会接受它。看看eslint和tslint中的 eqeqeq或三等号规则...

明确的方法,当我们检查一个变量是否是undefinednull单独的,应该在这种情况下应用,我对这个主题的贡献(现在有 27 个非否定答案!)是void 0用作执行检查的既短又安全的方法为undefined.

使用foo === undefined是不安全的,因为 undefined 不是保留字并且可以被隐藏(MDN)。使用typeof === 'undefined'check 是安全的,但如果我们不关心 foo-is-undeclared 的情况,可以使用以下方法:

if (foo === void 0 || foo === null) { ... }
于 2020-03-16T23:27:50.327 回答
2

如果您创建一个函数来检查它:

export function isEmpty (v) {
 if (typeof v === "undefined") {
   return true;
 }
 if (v === null) {
   return true;
 }
 if (typeof v === "object" && Object.keys(v).length === 0) {
   return true;
 }

 if (Array.isArray(v) && v.length === 0) {
   return true;
 }

 if (typeof v === "string" && v.trim().length === 0) {
   return true;
 }

return false;
}
于 2020-05-11T06:09:12.213 回答
0

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

于 2014-03-06T11:24:28.123 回答
0
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

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

于 2015-08-15T07:18:31.183 回答
0
var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}
于 2016-12-04T00:10:19.773 回答
0

我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:

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
}
于 2017-05-31T07:47:29.247 回答
-1

最好的办法:

if(typeof variable==='undefined' || variable===null) {

/* do your stuff */
}
于 2016-05-25T11:55:10.550 回答
-1

我知道我迟到了 10 年。但是我会在这里留下我的答案,以防万一有人需要一个简短的方法。

在您的项目中安装Lodash可能会很有用,因为在这些情况下可以派上用场的辅助函数。

使用 ES6 模块,导入将如下所示:

import isNull from 'lodash/isNull';

import isUndefined from 'lodash/isUndefined';

import isNil from 'lodash/isNil';

如果只导入使用过的函数会更好。

Lodash 的isNull检查值是否为空。

const value = null;
 
 if(isNull(value)) {
    // do something if null
 }

lodash 的isUndefined检查值是否未定义。

const value = undefined;

if(isUndefined(value)) {
   // do something if undefined.
}

isNil检查值是否为空未定义。与其他两种方法相比,我更喜欢这种方法,因为它同时检查 undefined 和 null。

于 2020-11-18T16:35:06.597 回答
-2

您可以通过简单地使用 typeof 来检查该值是否为 undefined 或 null:

if(typeof value == 'undefined'){
于 2017-07-26T02:16:47.980 回答
-3
Simplest answer: 

如果(!EmpName){做某事};

于 2021-03-30T21:48:54.690 回答
-4

if(x==null)在 JavaScript 中是个坏主意。用 - 判断"=="可能会导致意外的类型强制,CoffeeScript 无法读取,千万 不要在条件判断中使用“==”或“!=”!

if(x)会更好,但要小心0 和 ""。它将被视为false,而不是与"!= null"is true的 equal 方法。

在此处输入图像描述

请参阅JavaScript 最佳实践

于 2017-08-05T05:06:16.483 回答