JavaScript 程序:检查变量是否为 undefined 或 null

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:检查 undefined 或 null

// program to check if a variable is undefined or null

function checkVariable(variable) {

    if(variable == null) {
        console.log('The variable is undefined or null');
    }
    else {
       console.log('The variable is neither undefined nor null');
    }
}

let newVariable;

checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);

输出

The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null

在上面的程序中,会检查一个变量是否等于nullnull==一起使用会同时检查nullundefined值。这是因为null == undefined的计算结果为true

以下代码

if(variable == null) { ... }

等同于

if (variable === undefined || variable === null) { ... }

示例 2:使用 typeof

// program to check if a variable is undefined or null

function checkVariable(variable) {

    if( typeof variable === 'undefined' || variable === null ) {
        console.log('The variable is undefined or null');
    }
    else {
       console.log('The variable is neither undefined nor null');
    }
}

let newVariable;

checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);

输出

The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null

对于undefined值,typeof运算符返回undefined。因此,您可以使用typeof运算符检查undefined值。此外,null值使用===运算符进行检查。

注意:我们不能对null使用typeof运算符,因为它返回object


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战