是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

当前回答

可以使用参数成为数组的参数滤器

函数validateAttributes(arg1、arg2、arg3、arg4){var args=对象.values(参数);return(args.filter(x=>x===null||!x))。长度<=0}console.log(validateAttributes('1',2,3,4));console.log(validateAttributes('1',2,3,null));console.log(validateAttributes('1',未定义,3,4));console.log(validateAttributes('1',2,'',4));console.log(validateAttributes('1',2,3,null));

其他回答

检查值是否未定义或为空的详细方法为:

return value === undefined || value === null;

您也可以使用==运算符,但这需要您了解所有规则:

return value == null; // also returns true if value is undefined

仅对未定义和null返回false:

返回值??假的

您可以使用零合并运算符??检查空值和未定义值。参见MDN文档

null ?? 'default string'; // returns "default string"

0 ?? 42;  // returns 0

(null || undefined) ?? "foo"; // returns "foo"
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);
}

仅使用“空值合并”检查未定义和空值

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