Skip to content

isEmpty

isEmpty 判空

用于判断一个值是否“空”。支持多种类型判空:null/undefined、字符串、数组、普通对象、Map/SetArrayBuffer/DataViewTypedArrayDate 等;并提供可选项控制字符串 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 后再判断空booleantrue
treatNaNEmpty数值 NaN 是否视为空booleantrue

返回值

名称说明类型
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
}