美文网首页
js检测数据类型的方法

js检测数据类型的方法

作者: 冬天的_太阳 | 来源:发表于2019-09-26 10:22 被阅读0次
  • 方式一: typeof
typeof 1;//'number'
typeof true;//'boolean'
typeof '';//'string'
typeof undefined;//'undefined'
typeof function (){};'function'
  • 方式二: instanceof
var arr = [];
arr instanceof Array;//true
arr instanceof Object;//true

但是只要是在原型链上出现过构造函数都会返回true,所以这个检测结果不很准确

  • 方式三: constructor
var arr = [];
arr.constructor === Array;//true
arr.constructor === Object;//false
//因为arr通过原型链查找到的constructor指向了Array,所以跟Object判断就是错误滴
  • 方式四: Object.prototype.toString.call()
    在Object基本类定义的这个toString()方法,是用来检测数据类型的;
    跟字符串、数字、布尔等原型上定义的toString()方法基本用法都是转换字符串的。
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call(''));//[object String]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(null));// [object Null]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call([]));// [object Array]
console.log(Object.prototype.toString.call({}));// [object Object]
console.log(Object.prototype.toString.call(/^$/));//[object RegExp]
console.log(Object.prototype.toString.call((function () {})));//[object Function]

相关文章

网友评论

      本文标题:js检测数据类型的方法

      本文链接:https://www.haomeiwen.com/subject/wjepuctx.html