出处

Object 对象 - JavaScript 教程 - 网道 —— tostring-的应用:判断数据类型

代码

  • 不同数据类型的 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]
  1. Object.prototype.toString.call(2) // "[object Number]"
  2. Object.prototype.toString.call('') // "[object String]"
  3. Object.prototype.toString.call(true) // "[object Boolean]"
  4. Object.prototype.toString.call(undefined) // "[object Undefined]"
  5. Object.prototype.toString.call(null) // "[object Null]"
  6. Object.prototype.toString.call(Math) // "[object Math]"
  7. Object.prototype.toString.call({}) // "[object Object]"
  8. 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”

  1. - 在上面这个`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

```