Skip to content

hasOwnProp

判断对象自身是否拥有指定属性(不遍历原型链)

引入版本

0.40.0

Demo

ts
import { hasOwnProp } from '@wyfex/iutils'

/**
 * ================== 正确情况 ==================
 */
const obj1: any = { name: 'Symbol(王独秀)', age: undefined, sex: null }
obj1.id = 1

console.log(hasOwnProp(obj1, 'name'))
console.log(hasOwnProp(obj1, 'id'))
console.log(hasOwnProp(obj1, 'age'))
console.log(hasOwnProp(obj1, 'sex'))

const sym = Symbol('age')
const obj2 = { [sym]: 18 }
console.log(hasOwnProp(obj2, sym))

const obj3 = Object.create({})
obj3.name = 'Symbol(王独秀)'
console.log(hasOwnProp(obj3, 'name'))

const obj4 = Object.create(null)
obj4.name = 'Symbol(王独秀)'
console.log(hasOwnProp(obj4, 'name'))

console.log('------------------ 分界线 ------------------')

/**
 * ================== 错误情况 ==================
 */
const protoObj = Object.create({ protoKey: 1 })
console.log(hasOwnProp(protoObj, 'protoKey'))
console.log(hasOwnProp({}, 'test'))
console.log(hasOwnProp(null, 'xxx'))
console.log(hasOwnProp(undefined, 'xxx'))
console.log(hasOwnProp(123, 'toString'))
console.log(hasOwnProp('', 'length'))
console.log(hasOwnProp([1, 2, 3], '0'))
console.log(hasOwnProp([1, 2, 3], 'length'))

基于 MIT 许可发布