instanceof

  • instanceof 用于判断一个对象的构造函数是什么?(判断数据类型的)
  • 语法:对象 instanceof 构造函数
  • 对象 instanceof 原型链上的任何一个构造函数,都会得到true ```javascript // function Person() {

// } // let p = new Person()

// console.log(p instanceof Person) // true 对象 instanceof 构造函数 // console.log(p instanceof Object) // true 对象 instanceof 原型链上的任何构造函数都是true

let arr = [3, 4, 5] // let arr = new Array(3, 4, 5) // console.log(arr instanceof Array) // true // console.log(arr instanceof Object) // true

// 数组 instanceof Array|Object true // 对象 instanceof Array false

// if (arr instanceof Array) { if (Array.isArray(arr)) { console.log(‘是数组’) } else if (arr instanceof Object) { console.log(‘是对象’) } else { console.log(‘其他类型’) }

  1. 使用typeofinstanceof判断数据类型:
  2. ```javascript
  3. function abc() {
  4. }
  5. // console.log(typeof 'hello')
  6. // console.log(typeof 123)
  7. // console.log(typeof undefined)
  8. // console.log(typeof true)
  9. // console.log(typeof abc) // function
  10. // console.log(typeof null) // object
  11. // console.log(typeof []) // object
  12. // console.log(typeof {}) // object
  13. function myTypeOf(n) {
  14. if (typeof n === 'string' || typeof n === 'number' || typeof n === 'boolean' || typeof n === 'undefined' || typeof n === 'function') {
  15. return typeof n
  16. } else {
  17. // 说明变量是 null 、[] 、{} 中的一个
  18. if (n instanceof Array) {
  19. return 'array'
  20. } else if (n instanceof Object) {
  21. return 'object'
  22. } else {
  23. return 'null'
  24. }
  25. }
  26. }
  27. console.log(myTypeOf(123))
  28. console.log(myTypeOf('hello'))
  29. console.log(myTypeOf(true))
  30. console.log(myTypeOf(undefined))
  31. console.log(myTypeOf(abc))
  32. console.log(myTypeOf(null))
  33. console.log(myTypeOf([]))
  34. console.log(myTypeOf({}))
  35. // ------------------------------------------------------
  36. function myTypeOf(n) {
  37. switch (typeof n) {
  38. case 'string':
  39. case 'number':
  40. case 'boolean':
  41. case 'undefined':
  42. case 'function':
  43. return typeof n
  44. default:
  45. if (n instanceof Array) {
  46. return 'array'
  47. } else if (n instanceof Object) {
  48. return 'object'
  49. } else {
  50. return 'null'
  51. }
  52. }
  53. }
  54. console.log(myTypeOf(123))
  55. console.log(myTypeOf('hello'))
  56. console.log(myTypeOf(true))
  57. console.log(myTypeOf(undefined))
  58. console.log(myTypeOf(abc))
  59. console.log(myTypeOf(null))
  60. console.log(myTypeOf([]))
  61. console.log(myTypeOf({}))