js中的in操作符

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

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值