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

js 判断不为空

作者:_o隨缘   发布日期:2025-03-30   浏览:107

// 判断变量不为空的几种常见方式

// 1. 使用 typeof 检查是否为 undefined
function isNotEmpty(value) {
    return typeof value !== 'undefined' && value !== null && value !== '';
}

// 2. 使用 Boolean 转换和空值合并运算符(??)
function isNotEmptyUsingNullish(value) {
    return (value ?? '') !== '';
}

// 3. 使用严格相等检查
function isNotEmptyStrict(value) {
    return value !== undefined && value !== null && value !== '';
}

// 示例用法
let testVar = "Hello World";
console.log(isNotEmpty(testVar)); // 输出: true
console.log(isNotEmptyUsingNullish(testVar)); // 输出: true
console.log(isNotEmptyStrict(testVar)); // 输出: true

testVar = null;
console.log(isNotEmpty(testVar)); // 输出: false
console.log(isNotEmptyUsingNullish(testVar)); // 输出: false
console.log(isNotEmptyStrict(testVar)); // 输出: false

解释说明:

  • isNotEmpty: 通过 typeof 检查变量是否为 undefined,并且确保它既不是 null 也不是空字符串。
  • isNotEmptyUsingNullish: 使用空值合并运算符 ?? 来处理 nullundefined 的情况,并确保它不是空字符串。
  • isNotEmptyStrict: 使用严格相等运算符 === 来确保变量既不是 undefined 也不是 null 或空字符串。

这些方法可以帮助你在 JavaScript 中有效地判断一个变量是否不为空。

上一篇:js 判断对象不为空

下一篇:js 判断对象为空

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

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

Laravel 中文站