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

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

当前回答

我认为使用?操作员稍微干净一点。

var ? function_if_exists() : function_if_doesnt_exist();

其他回答

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

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

这是我检查数据是否为空的解决方案。

const _isEmpty = (data) => {
  return (
    // this way we can also check for undefined values. null==undefined is true
    data == null ||
    data == "" ||
    (Array.isArray(data) && data.length === 0) ||
    // we want {} to be false. we cannot use !! because !!{} turns to be true
    // !!{}=true and !!{name:"yilmaz"}=true. !! does not work ofr objects
    (data.constructor === Object && Object.keys(data).length === 0)

  );
};

您可能会发现以下函数很有用:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

或在ES7中(如有进一步改进,请发表评论)

function typeOf(obj) {
  const { toString } = Object.prototype;
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);

  return type.toLowerCase();
}

结果:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map

“请注意,绑定运算符(::)根本不是ES2016(ES7)的一部分,也不是ECMAScript标准的任何后续版本。它目前是引入语言的第0阶段(strawman)建议。”–Simon Kjellberg。作者希望补充他对这个接受王室提升的美好提议的支持。

第一个评分最好的答案是错误的。若值未定义,则会在现代浏览器中引发异常。您必须使用:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)

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

函数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));