美文网首页
js中判断变量为空的方法isEmpty

js中判断变量为空的方法isEmpty

作者: 大兵_HERG | 来源:发表于2019-08-13 11:41 被阅读0次

isEmpty方法封装

function isEmpty (val) {
  // null or undefined
  if (val == null) return true;

  if (typeof val === 'boolean') return false;

  if (typeof val === 'number') return !val;

  if (val instanceof Error) return val.message === '';

  switch (Object.prototype.toString.call(val)) {
    // String or Array
    case '[object String]':
    case '[object Array]':
      return !val.length;

    // Map or Set or File
    case '[object File]':
    case '[object Map]':
    case '[object Set]': {
      return !val.size;
    }
    // Plain Object
    case '[object Object]': {
      return !Object.keys(val).length;
    }
  }

  return false;
}
isEmpty("")
//true
isEmpty([])
//true
isEmpty({})
//true
isEmpty(0)
//true
isEmpty(undefined)
//true
isEmpty(null)
//true
isEmpty(1)
//false

相关文章

网友评论

      本文标题:js中判断变量为空的方法isEmpty

      本文链接:https://www.haomeiwen.com/subject/lhsvjctx.html