Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 判断变量是否为空

作者:浪子罢了   发布日期:2026-06-11   浏览:71

// 判断变量是否为空的几种常见方法

// 方法1: 使用 typeof 检查变量是否未定义
function isUndefined(variable) {
  return typeof variable === 'undefined';
}

// 方法2: 检查变量是否为 null
function isNull(variable) {
  return variable === null;
}

// 方法3: 检查变量是否为 undefined 或 null
function isNullOrUndefined(variable) {
  return variable == null; // 这里使用 == 可以同时检查 null 和 undefined
}

// 方法4: 检查变量是否为空字符串、null、undefined 或者 false
function isEmpty(variable) {
  return variable == null || variable === '' || variable === false;
}

// 示例用法
let testVar;

console.log(isUndefined(testVar)); // true
console.log(isNull(null)); // true
console.log(isNullOrUndefined(undefined)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(false)); // true
console.log(isEmpty('hello')); // false

解释说明:

  1. isUndefined: 检查变量是否未定义,使用 typeof 操作符。
  2. isNull: 检查变量是否为 null,使用严格相等操作符 ===
  3. isNullOrUndefined: 同时检查变量是否为 nullundefined,使用宽松相等操作符 ==
  4. isEmpty: 检查变量是否为 nullundefined、空字符串或 false,适用于更广泛的场景。

这些方法可以根据具体需求选择使用。

上一篇:js 数组转json

下一篇:js 大写字母转小写

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站