admin 发表于 2024-4-26 11:34:44

js判断变量是否有值是否为null或undefined

在JavaScript中,可以使用typeof运算符来检查一个变量是否具有值,或者使用== null来检查变量是否为null或undefined。以下是检查变量是否具有值的代码示例:

function hasValue(variable) {
return variable !== null && variable !== undefined && variable !== '';
}

// 示例使用
const myVariable = 'some value';
if (hasValue(myVariable)) {
console.log('变量有值');
} else {
console.log('变量无值');
}如果你只关心变量是否是undefined或null,可以这样写:

function isDefined(variable) {
return variable !== null && variable !== undefined;
}

// 示例使用
const myVariable = null;
if (isDefined(myVariable)) {
console.log('变量有值或是空字符串');
} else {
console.log('变量无值或是undefined/null');
}这些函数将帮助你检查变量是否有实际的值,而不是undefined、null或空字符串。

页: [1]
查看完整版本: js判断变量是否有值是否为null或undefined