是否有一个通用的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;
}
当前回答
! 检查空字符串(“”)、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或!!价值。
其他回答
可以直接使用相等运算符
<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确定变量是否未定义或为空
这是最安全的支票,我还没有看到它像这样贴在这里:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
它将涵盖从未定义价值的情况,以及以下任何情况:
无效的undefined(未定义的值与从未定义的参数不同)0“”(空字符串)假的NaN公司
已编辑:更改为严格相等(!==),因为这是现在的标准;)
下面是我的工作。请稍微改变一下,以加快速度
function isEmpty(obj) {
if (!obj) return true;
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return 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
function isEmpty(val){
return !val;
}
但是这个解决方案是过度设计的,如果您不想稍后根据业务模型的需要修改函数,那么直接在代码中使用它会更干净:
if(!val)...