JS判断变量类型的方法总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32657025/article/details/79684679

typeof操作符

用于检测基本数据类型,返回值可能为:

  • “number”
  • “boolean”
  • “string”
  • “undefined”
  • “object”
  • “function”.

注意:typeof null返回”object”。

instanceof操作符

用于检测某一个对象是否为某一类型的实例。

[3,4,5] instanceof Array
//true

Object.prototype.toString()方法

Object对象的toString()在未被自定义对象覆盖时, 返回 “[object type]”,其中type是对象的类型。因此,可以用于变量类型检测。

let arr = [3,4,5]
Object.prototype.toString.call(arr);
//"[object Array]"

let num = 123;
Object.prototype.toString.call(num);
//"[object Number]"

猜你喜欢

转载自blog.csdn.net/qq_32657025/article/details/79684679