// 判断变量是否为空的几种常见方法
// 方法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
typeof 操作符。null,使用严格相等操作符 ===。null 或 undefined,使用宽松相等操作符 ==。null、undefined、空字符串或 false,适用于更广泛的场景。这些方法可以根据具体需求选择使用。
上一篇:js 数组转json
下一篇:js 大写字母转小写
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站