_.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