Appearance
isEmpty
isEmpty 判空
用于判断一个值是否“空”。支持多种类型判空:null/undefined、字符串、数组、普通对象、Map/Set、ArrayBuffer/DataView、TypedArray、Date 等;并提供可选项控制字符串 trim 与数值 NaN 的判空行为。
一、引入与使用
支持两种方式引入:
ts
// 方式一:按需子路径引入(推荐)
import { isEmpty } from '@cuixingjian/cui-utils/isEmpty'
// 方式二:从包入口命名导出引入
import { isEmpty } from '@cuixingjian/cui-utils'二、使用示例
ts
import { isEmpty } from '@cuixingjian/cui-utils/isEmpty'
// 基本类型
isEmpty(null) // true
isEmpty(undefined) // true
isEmpty('') // true
isEmpty(' ') // true(默认 trimString: true)
isEmpty(0) // false
isEmpty(NaN) // true(默认 treatNaNEmpty: true)
// 引用类型
isEmpty([]) // true
isEmpty({}) // true
isEmpty(new Map()) // true
isEmpty(new Set()) // true
isEmpty(new Date('invalid')) // true(无效日期)
// 关闭字符串 trim 判空
isEmpty(' ', { trimString: false }) // false
// 关闭 NaN 判空
isEmpty(NaN, { treatNaNEmpty: false }) // false三、API
| 方法 | 说明 | 类型 |
|---|---|---|
| isEmpty | 判断一个值是否为空 | (value: any, options?: IsEmptyOptions) => boolean |
参数
| 参数名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 待判断的值 | any | — |
| options | 判空选项 | IsEmptyOptions | { trimString: true, treatNaNEmpty: true } |
IsEmptyOptions
| 字段 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| trimString | 字符串是否 trim 后再判断空 | boolean | true |
| treatNaNEmpty | 数值 NaN 是否视为空 | boolean | true |
返回值
| 名称 | 说明 | 类型 |
|---|---|---|
| result | 是否为空 | boolean |
四、注意事项
- 普通对象仅在无自有键(
Reflect.ownKeys(obj).length === 0)时视为空;原型链上的属性不计入。 TypedArray使用length判断;ArrayBuffer/DataView使用byteLength判断。Date无效(getTime()为NaN)视为空。- 其他类型(如布尔、函数、正则、Promise 等)默认不视为空。
五、源码
展开查看
ts
// 源码来自 @cuixingjian/cui-utils/isEmpty
export interface IsEmptyOptions {
trimString?: boolean
treatNaNEmpty?: boolean
}
function isPlainObject(val: any): val is Record<string | symbol, any> {
if (val === null || typeof val !== 'object') return false
const proto = Object.getPrototypeOf(val)
return proto === Object.prototype || proto === null
}
export function isEmpty(value: any, options: IsEmptyOptions = {}): boolean {
const { trimString = true, treatNaNEmpty = true } = options
if (value == null) return true
const t = typeof value
if (t === 'string') {
const s = trimString ? value.trim() : value
return s.length === 0
}
if (t === 'number') {
return treatNaNEmpty && Number.isNaN(value)
}
if (Array.isArray(value)) return value.length === 0
if (ArrayBuffer.isView(value)) {
// @ts-ignore
if (typeof value.length === 'number') return value.length === 0
// @ts-ignore
if (typeof value.byteLength === 'number') return value.byteLength === 0
}
if (value instanceof ArrayBuffer) return value.byteLength === 0
if (value instanceof DataView) return value.byteLength === 0
if (value instanceof Map || value instanceof Set) return value.size === 0
if (value instanceof Date) return Number.isNaN(value.getTime())
if (isPlainObject(value)) return Reflect.ownKeys(value).length === 0
return false
}