肖强的博客 肖强的博客
Home
Guide
Web Document
  • Plugins
  • Case
  • Animation
Components
  • Categories
  • Tags
  • Archives
Website Tools

xiaoQiang

因为爱所以爱
Home
Guide
Web Document
  • Plugins
  • Case
  • Animation
Components
  • Categories
  • Tags
  • Archives
Website Tools
  • JavaScript

    • 01.基础
    • 02.内置对象
    • 03.面向对象
    • 04.异步操作
    • 05.DOM
    • 06.事件
    • 07.浏览器模型
    • 08.new命令原理
    • 09.ES5面向对象
    • 10.ES6面向对象
    • 11.多种数组去重性能对比
    • 12.js随机打乱数组
    • 13.判断是否为移动端浏览器
    • 14.将一维数组按指定长度转为二维数组
    • 15.防抖与节流函数
    • 16.JS获取和修改url参数
    • 17.比typeof运算符更准确的类型判断
  • views
xiaoQiang
2020-04-13

比typeof运算符更准确的类型判断

# 比typeof运算符更准确的类型判断

不同数据类型的Object.prototype.toString方法返回值如下。

  • 数值:返回[object Number]。
  • 字符串:返回[object String]。
  • 布尔值:返回[object Boolean]。
  • undefined:返回[object Undefined]。
  • null:返回[object Null]。
  • 数组:返回[object Array]。
  • arguments 对象:返回[object Arguments]。
  • 函数:返回[object Function]。
  • Error 对象:返回[object Error]。
  • Date 对象:返回[object Date]。
  • RegExp 对象:返回[object RegExp]。
  • 其他对象:返回[object Object]。

这就是说,Object.prototype.toString可以看出一个值到底是什么类型。

Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"

利用这个特性,可以写出一个比typeof运算符更准确的类型判断函数。

var type = function (o){
    var s = Object.prototype.toString.call(o)
    return s.match(/\[object (.*?)\]/)[1].toLowerCase()
}
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"

在上面这个type函数的基础上,还可以加上专门判断某种类型数据的方法。

var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

['Null',
 'Undefined',
 'Object',
 'Array',
 'String',
 'Number',
 'Boolean',
 'Function',
 'RegExp'
].forEach(function (t) {
  type['is' + t] = function (o) {
    return type(o) === t.toLowerCase();
  };
});

type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true
#JavaScript
上次更新: 2021-10-06 15:11:51
16.JS获取和修改url参数

← 16.JS获取和修改url参数

最近更新
01
drag
12-22
02
入场/出场05
10-16
03
入场/出场04
10-16
更多文章>
icon组件不能用
时间左侧 © 2021-2021 时间右侧
冀公网安备 13108202000744号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
欢迎来到我的家
Back