// 判断变量是否为空的几种常见方式
// 1. 使用 typeof 判断 undefined
function isEmpty(value) {
return typeof value === 'undefined';
}
// 2. 使用 null 和 undefined 判断
function isNullorUndefined(value) {
return value == null; // 这里会同时判断 null 和 undefined
}
// 3. 判断空字符串
function isEmptyString(value) {
return value === '';
}
// 4. 综合判断 (null, undefined, 空字符串, NaN)
function isBlank(value) {
return value == null || value === '' || isNaN(value);
}
// 示例用法
console.log(isEmpty(undefined)); // true
console.log(isNullorUndefined(null)); // true
console.log(isEmptyString("")); // true
console.log(isBlank(NaN)); // true
console.log(isBlank("")); // true
console.log(isBlank(null)); // true
console.log(isBlank(undefined)); // true
console.log(isBlank("hello")); // false
isEmpty 函数用于判断变量是否为 undefined。isNullorUndefined 函数用于判断变量是否为 null 或 undefined,使用 == null 可以同时匹配这两种情况。isEmptyString 函数用于判断变量是否为空字符串 ""。isBlank 函数是一个综合判断函数,可以同时判断变量是否为 null、undefined、空字符串或 NaN。这些方法可以帮助你在 JavaScript 中有效地判断变量是否为空。
上一篇:js 判断字符串不为空
下一篇:js 判断对象不为空
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站