重学JS-数据类型及类型检测

40次阅读

共计 2237 个字符,预计需要花费 6 分钟才能阅读完成。

数据类型

JavaScript 七种内置类型:

  • 空值(null)
  • 未定义(undefined)
  • 布尔值(boolean)
  • 数字(number)
  • 字符串(string)
  • 对象(object)
  • 符号(symbol)

除对象之外,其他统称为基本类型

类型检测

typeof

typeof 运算符后面跟操作数,typeof operand 或者 typeof (operand),返回一个类型的字符串值。

示例:

typeof undefined === "undefined" // true
typeof true === "boolean" // true
typeof 1 === "number" // true
typeof 'test' === "string" // true
typeof {} === "object" // true
typeof Symbol() === "symbol" // true

特殊示例:

typeof null === "object"
typeof function () {} === "function"
typeof [1] === "object"

typeof 对 null 的处理有问题,正确的结果应该是 ”null”,但是实际返回的是 ”object”,这个 bug 由来已久,也许以后也不会修复。

typeof function() {} 返回的是一个 ”function”,似乎 function 也是 JavaScript 的一个内置对象,实际上函数是一个可调用对象,它有一个内部属性 [[Call]],该属性使其可以被调用。

typeof [1] 返回 ”object”,说明数组也是 object 类型,实际上它是 object 的一个子类型,和普通对象通过字符串键索引不同,数组通过数字按顺进行索引。

总结表格:

instance

typeof 是检测基本数据类型的最佳工具,但是检测引用类型的值时作用不大,都会返回 ”object”,这时候就需要 instance 操作符了。instance 运算符用于测试构造函数的 protytpe 属性是否出现在对象的原型链中的任何位置。

用法:object instanceof constructor,object: 要检测的对象,constructor 某个构造函数

示例:

function A() {}
function B() {}
function C() {}
A.prototype = new C()
const a = new A()
console.log(a instanceof A) // a 是 A 类的实例 true
console.log(a instanceof C) // A 继承 C true
console.log(a instanceof B) // a 不是 A 类的实例 false
console.log(a instanceof Object) // Object 实所有引用类型的父类 true
console.log(A.prototype instanceof Object) // true
A.prototype = {}
a1 = new A()
console.log(a1 instanceof A) // true
console.log(a instanceof A) // false
const date = new Date()
console.log(date instanceof Date) // true

原理

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
 var O = R.prototype;// 取 R 的显示原型
 L = L.__proto__;// 取 L 的隐式原型
 while (true) {if (L === null) 
     return false; 
   if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
     return true; 
   L = L.__proto__; 
 } 
}

想要对 instanceof 运算符有更加深入的了解车票

toString

toString() 方法返回一个表示该对象的字符串,每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 ”[object type]”,其中 type 是对象的类型

示例

const toString = Object.prototype.toString
console.log(toString.call(null)) // [object Null]
console.log(toString.call(undefined)) // [object Undefined]
console.log(toString.call(new String)) // [object String]
console.log(toString.call(Function)) // [object Function]
console.log(toString.call(new Date)) // [object Date]
console.log(toString.call('new Date')) // [object String]
console.log(toString.call(['a'])) // [object Array]

从示例可以看出,Object.prototype.toString.call() 可以准确表示数值的类型

总结

  • typeof 运算符适合检测基本数据类型,且返回类型的字符串
  • instanceof 运算符适合检测引用类型值
  • toString() 返回对象的类型,可以准确判断数值的类型

正文完
 0