最简单的方式理解typeof、instanceof、hasOwnProperty

1.typeof

语法: typeof 判断值
返回数据类型值
需要注意:返回的数据类型是字符串值,并且首字母小写
看下面例子:

		let str = '1'
        let str1 = 1
        let str2 = true
        let str3 = () => { }
        let str4 = [1, 2, 3]
        let str5 = {
            name: "zjq",
            age: 18,
            habby: ['唱歌', "跳舞", '游泳']
        }
        console.log(typeof str)  //string  字符串string
        console.log(typeof str1) //number  字符串number
        console.log(typeof str2) //boolean 字符串boolean
        console.log(typeof str3) //function 字符串function
        console.log(typeof str4) //object  字符串object   ***
        console.log(typeof str5) //object  字符串object
        //判断数组一般用这个
        console.log(Array.isArray(str4)) //true 

2.instanceof

语法: 判断值(必须是个对象) instanceof 数据类型
返回布尔类型 true\false
需要注意:判断值必须是一个对象,否者直接直接false
看下面例子:

		let str = '1'
        let str1 = 1
        let str2 = true
        let str3 = () => { }
        let str4 = [1, 2, 3]
        let str5 = {
            name: "zjq",
            age: 18,
            habby: ['唱歌', "跳舞", '游泳']
        }
        //对象 instanceof   类型 
        let strcopy = new String('1')
        console.log(str instanceof String)  //false   
        console.log(strcopy instanceof String)  //true   
        console.log(str1 instanceof Number) // false
        console.log(str2 instanceof Boolean) //  false
        console.log(str3 instanceof Function) // true
        console.log(str4 instanceof Array) //  true
        console.log(str5 instanceof Object) //  true

3.hasOwnProperty

语法: 对象.hasOwnProperty(属性名) || Object.prototype.hasOwnProperty.call(对象,属性名 )
返回布尔类型 true\false
需要注意:hasOwnProperty只能判断对象本身是否含有这个属性
看下面例子:

//hasOwnProperty 只能判断对象本身是否含有这个属性 
        //不能判断原型链
        let obj = {
            name: "zjq",
            age: 18,
            habby: ['唱歌', "跳舞", '游泳']
        }
        obj.__proto__.run ='100'
        console.log(Object.prototype.hasOwnProperty.call(obj, 'name')) //true
        console.log(obj.hasOwnProperty('age')) //true
        console.log(obj.hasOwnProperty('run'))  //false

typeof、instanceof是判断数据类型
hasOwnProperty是判断这个对象是否含有这个属性

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六卿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值