isEmpty.js 2.1 KB
Newer Older
1 2 3 4 5 6
import getTag from './getTag.js';
import isArguments from './isArguments.js';
import isArrayLike from './isArrayLike.js';
import isBuffer from './isBuffer.js';
import isPrototype from './isPrototype.js';
import isTypedArray from './isTypedArray.js';
徐立's avatar
徐立 committed
7 8

/** Used to check objects for own properties. */
9
const hasOwnProperty = Object.prototype.hasOwnProperty;
徐立's avatar
徐立 committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

/**
 * Checks if `value` is an empty object, collection, map, or set.
 * 检查' value '是否为空对象、集合、映射或集合。
 * 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`.
 * 类似数组的值,如‘arguments’对象、数组、缓冲区、字符串或
 * 类似于jquery的集合如果“长度”为“0”,就会被认为是空的。
 * 类似地,如果映射和集合的“size”为“0”,则认为它们是空的。
 * @since 0.1.0
 * @category Lang
 * @param {*} value 要检查的值。
 * @returns {boolean} 如果' value '为空,则返回' true ',否则返回' false '。
 * @example
 *
 * isEmpty(null)
 * // => true
 *
 * isEmpty(true)
 * // => true
 *
 * isEmpty(1)
 * // => true
 *
 * isEmpty([1, 2, 3])
 * // => false
 *
 * isEmpty('abc')
 * // => false
 *
 * isEmpty({ 'a': 1 })
 * // => false
 */
function isEmpty(value) {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	if (value == null) {
		return true;
	}
	if (
		isArrayLike(value) &&
		(Array.isArray(value) ||
			typeof value === 'string' ||
			typeof value.splice === 'function' ||
			isBuffer(value) ||
			isTypedArray(value) ||
			isArguments(value))
	) {
		return !value.length;
	}
	const tag = getTag(value);
	if (tag == '[object Map]' || tag == '[object Set]') {
		return !value.size;
	}
	if (isPrototype(value)) {
		return !Object.keys(value).length;
	}
	for (const key in value) {
		if (hasOwnProperty.call(value, key)) {
			return false;
		}
	}
	return true;
徐立's avatar
徐立 committed
76 77
}

78
export default isEmpty;