Skip to content
大纲

js类型判断

typeOf

  1. typeof操作符一般用来检测基本数据类型,返回以下某个字符串:'undefined', 'boolean', 'number', 'string', 'object', 'function'。
  2. null, Array, Date, RegExp, Object都返回'object'。
  3. function虽然也是对象的一种,但是函数具有某些特殊属性,因此通过typeof来区分函数和其他对象是有必要的
js
typeof(99)

instabceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

js
class Lei {
    
  }

  let temp = new Lei()
  console.log(temp instanceof Lei, temp.__proto__ === Lei.prototype)

字符串

js
let str = 'str'
let str2 = String('str')
let str3 = new String('str')
typeof(str) // string
typeof(str2) // string
typeof(str3) // Object

str.__proto // String
str2.__proto // String
str3.__proto // String

let str4 = str3 + ''
typeof(str4) // string
str4.__proto // String

数组判断

  1. instanceof arr instanceof Array
  2. proto arr._proto === Array.prototype
  3. Object.prototype.toString Object.prototype.tostring.call(arr) === '[objdect Array]'
  4. Array.isArray() Array.isArray(arr)
  5. constructor arr.constractor === Array

对象判断

  1. typeof 只能判断基本类型
  2. instanceof obj intancepof Object
  3. constructor obj.contractor === Object
  4. Object.prototype.toString Object.prototype.tostring.call(obj) === '[objdect Object]'

Released under the MIT License.