Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

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

用于检查变量是否未定义或为空的 JavaScript 程序

在本例中,您将学习编写一个 JavaScript 程序,该程序将检查变量是否未定义或为空。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript null 和未定义 JavaScript typeof 运算符 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 运算符,因为它返回对象。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4