是否有一个通用的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;
}
当前回答
您可以使用零合并运算符??检查空值和未定义值。参见MDN文档
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
其他回答
! 检查空字符串(“”)、null、undefined、false以及数字0和NaN。例如,如果字符串为空var name=“”,那么console.log(!name)返回true。
function isEmpty(val){
return !val;
}
如果val为空、null、undefined、false、数字0或NaN,则此函数将返回true。
OR
根据您的问题域,您可以使用like!val或!!价值。
我认为使用?操作员稍微干净一点。
var ? function_if_exists() : function_if_doesnt_exist();
可以直接使用相等运算符
<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;
}
当引用或函数可能未定义或为空时,可选的链接运算符提供了一种简化通过连接对象访问值的方法。
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;
可以在可选链接之后使用零合并运算符,以便在未找到任何值时构建默认值:
let customer = {
name: "Carl",
details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city