是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
当前回答
仅使用“空值合并”检查未定义和空值
if ((myVariable ?? undefined) !== undefined) {
// handle myVariable has a value, including 0 or ""
}
else {
// handle undefined or null only
}
来自铬控制台
{const x=undefined; (x ?? undefined) !== undefined}
false
{const x=null; (x ?? undefined) !== undefined}
false
{const x=0; (x ?? undefined) !== undefined}
true
{const x=""; (x ?? undefined) !== undefined}
true
{const x={}; (x ?? undefined) !== undefined}
true
{const x=[]; (x ?? undefined) !== undefined}
true
{const x="a"; (x ?? undefined) !== undefined}
true
其他回答
return val || 'Handle empty variable'
是在许多地方处理它的一种非常好且干净的方法,也可以用于分配变量
const res = val || 'default value'
可以直接使用相等运算符
<script>
var firstName;
var lastName = null;
/* Since null == undefined is true, the following statements will catch both null and undefined */
if(firstName == null){
alert('Variable "firstName" is undefined.');
}
if(lastName == null){
alert('Variable "lastName" is null.');
}
</script>
demo@如何使用JavaScript确定变量是否未定义或为空
这里是我的-如果值为null、undefined等或空白(即仅包含空格),则返回true:
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
function isEmpty(value){
return (value == null || value.length === 0);
}
对于
undefined // Because undefined == null
null
[]
""
和零参数函数,因为函数的长度是它所使用的声明参数的数量。
要禁止后一个类别,您可能只需要检查空白字符串
function isEmpty(value){
return (value == null || value === '');
}
Null或空白
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
检查值是否未定义或为空的详细方法为:
return value === undefined || value === null;
您也可以使用==运算符,但这需要您了解所有规则:
return value == null; // also returns true if value is undefined