_.isEmpty(value)


135

_.isEmpty(value)
判断一个值是否是一个空对象,空集合,空map,空set
如果一个对象没有自身可枚举的字符串键属性就说明它是空对象
array-like对象例如arguments对象,array,buffer,string,jquery-like集合对象如果它们的length属性等于0就说明它们是空的。
map和set对象如果它们的size属性等于0就说明是空的

参数

value (*): 需要检查的值

返回值

(boolean): 如果是空对象返回true,否则false

例子

_.isEmpty(null);
// => true
 
_.isEmpty(true);
// => true
 
_.isEmpty(1);
// => true
 
_.isEmpty([1, 2, 3]);
// => false
 
_.isEmpty({ 'a': 1 });
// => false

源代码

import getTag from './.internal/getTag.js'
import isArguments from './isArguments.js'
import isArrayLike from './isArrayLike.js'
import isBuffer from './isBuffer.js'
import isPrototype from './.internal/isPrototype.js'
import isTypedArray from './isTypedArray.js'

/** Used to check objects for own properties. */
//Object.prototype.hasOwnProperty判断属性是否是对象自身属性
const hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * isEmpty(null)
 * // => true
 *
 * isEmpty(true)
 * // => true
 *
 * isEmpty(1)
 * // => true
 *
 * isEmpty([1, 2, 3])
 * // => false
 *
 * isEmpty('abc')
 * // => false
 *
 * isEmpty({ 'a': 1 })
 * // => false
 */
//判断一个值是否是一个空对象,空集合,空map,空set
//如果一个对象没有自身可枚举的字符串键属性就说明它是空对象
//array-like对象例如arguments对象,array,buffer,string,jquery-like集合对象如果它们的length属性等于0就说明它们是空的。
//map和set对象如果它们的size属性等于0就说明是空的
function isEmpty(value) {
  if (value == null) {//如果等于null,返回true
    return true
  }
  if (isArrayLike(value) &&
      (Array.isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
        isBuffer(value) || isTypedArray(value) || isArguments(value))) {
      //如果是array-like对象并且
      //如果是array或者string或者有splice方法属性或者是buffer或者是typeArray或者是arguments
      //就判断length是否等于0
    return !value.length
  }
  const tag = getTag(value)//获取value的toStringTag
  if (tag == '[object Map]' || tag == '[object Set]') {//如果是map和set就判断size属性是否等于0
    return !value.size
  }
  if (isPrototype(value)) {//如果value是原型对象,就判断是否自身可枚举字符串键属性长度为0
    return !Object.keys(value).length
  }
  for (const key in value) {//否则用for in循环,如果有自身可枚举属性存在,返回false,否则返回true
    if (hasOwnProperty.call(value, key)) {
      return false
    }
  }
  return true
}

export default isEmpty

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM