in & hasOwnProperty

206 阅读1分钟

对象

测试代码

const bruce = {
  self_prop: 'bruce',
}
Object.setPrototypeOf(bruce, {'extend_prop': 233})
let self_symbol = Symbol('self_symbol')
// 加入symbol属性
bruce[self_symbol] = "secret";
// 不可枚举属性
Object.defineProperty(bruce, 'self_non_enumerable', {
  enumerable: false,
  value: 'unKnow'
})

in

包含自身及继承属性

console.log('self_prop' in bruce)   // true
console.log(self_symbol in bruce)  // true
console.log('self_non_enumerable' in bruce)   // true
console.log('extend_prop' in bruce)  // true

hasOwnProperty

不包含继承属性

console.log(bruce.hasOwnProperty('self_prop'))   // true
console.log(bruce.hasOwnProperty(self_symbol)  // true
console.log(bruce.hasOwnProperty('self_non_enumerable'))  // true
console.log(bruce.hasOwnProperty('extend_prop'))   // false

数组

测试代码

const arr = ['foo', 'bar', , 'baz'];
const arr2 = ['foo', 'bar',undefined , 'baz'];
arr.describe = 'just array~';

in

console.log('1' in arr)   // true
console.log(1 in arr)   // true
console.log(2 in arr)    // false
console.log(2 in arr2)    // true
console.log('describe' in arr)  //true

hasOwnProperty

console.log(Object.prototype.hasOwnProperty.call(arr, '1'))  // true
console.log(Object.prototype.hasOwnProperty.call(arr, 1)) // true
console.log(Object.prototype.hasOwnProperty.call(arr, 2))  // false
console.log(Object.prototype.hasOwnProperty.call(arr2, 2))  // true
console.log(Object.prototype.hasOwnProperty.call(arr, 'describe')) // true

对于数组in和hasOwnProperty是相同的