温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用 instanceof 判断数据类型

发布时间:2020-03-05 09:49:15 来源:网络 阅读:1197 作者:Cherish纯紫 栏目:开发技术

instanceof:的作用就是检测构造函数的 prototype 和 实例的原型__proto__是否相等。

  • String 和 Date 对象同时也属于Object 类型
    console.log(String.prototype.__proto__ === Object.prototype) // true
    console.log(Date.prototype.__proto__ === Object.prototype)  // true
  • 如果通过 字面量 的方式创建字符串,那么无法通过 instanceof 判断某个变量是否是字符串
    let str2 = 'aaaa'
    console.log(str2 instanceof String) // false
    console.log(str2 instanceof Object) // false
  • 通过 new 方式,是可以使用 instanceof 判断 变量是否是字符串。
    let str1 = new String('aaa')
    console.log(str1 instanceof String) // true
    console.log(str1 instanceof Object) // true
    console.log(str1.__proto__ === String.prototype) // true
  • 对于复杂数据类型 对象 和 数组,无论是通过字面量的方式创建,还是 new 的方式,都是可以通过 instanceof 来判断数据类型的
class Dog {
  constructor(name) {
    this.name = name
    this.type = 'dog'
  }
}

let d1 = new Dog('大黄')
let d2 = { name: '肉肉' }
console.log(d1)  //  { name: '大黄', type: 'dog' }
console.log(d2) // { name: '肉肉' }
console.log(d1 instanceof Dog)  // true
console.log(d1 instanceof Object) // true
console.log(d2 instanceof Object)  // true

let arr1 = [1, 2]
let arr2 = new Array('a', 'b')
console.log(arr1 instanceof Array) // true
console.log(arr2 instanceof Array) // true
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI