in 操作符用来判断属性是否存在于对象中,无论该属性存在于实例中还是原型中。
基本用法
var obj = {
keys: ['none','false'],
ShadowRoot: true
}
console.log('keys' in obj) // true
console.log('ShadowRoot' in obj) // true
console.log('name' in obj) // false
对于数组属性需要指定数字形式的索引值来表示数组的属性名称,不包括length属性
var arr = [1,2,3]
console.log(0 in arr) // true
console.log(1 in arr) // true
console.log(2 in arr) // true
// 如果删除掉某个元素,再打印一下看看
delete arr[1]
console.log(1 in arr) // false
in右边必须是对象。如果是一个string必须是包装类型
let a = new String('jklove')
let b = 'jklove'
console.log(2 in a) // true
console.log(2 in b) // TypeError: Cannot use 'in' operator to search for '2' in jklove
in和Object.hasOwnProperty()的区别
Object.hasOwnProperty()是检查对象是否包含非继承属性,而in是检查对象是否包含某个属性,不管是不是继承属性
function Student(name, age) {
this.name = name
this.age = age
}
Student.prototype.address = '上海'
console.log('name' in new Student()) // true
console.log(Object.hasOwnProperty.call(Student, 'name')) // true
console.log('address' in new Student()) // true
console.log(Object.hasOwnProperty.call(Student, 'address')) // false