能够经过toString()
来获取每一个对象的类型。为了每一个对象都能经过 Object.prototype.toString()
来检测,须要以 Function.prototype.call()
或者 Function.prototype.apply()
的形式来调用,传递要检查的对象做为第一个参数,称为thisArg
。app
var toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] //Since JavaScript 1.8.5 toString.call(undefined); // [object Undefined] toString.call(null); // [object Null]
能够写个函数来判断个数据类型函数
function consoleType(obj) { return (Object.prototype.toString.apply(obj)); } consoleType([]); // [object Array] consoleType(null); // [object Null] consoleType(undefined); // [object Undefined] consoleType(0); // [object Number] consoleType(new Date); // [object Date] consoleType({}); // [object Object] consoleType(function () {}); // [object Function] consoleType(NaN); // [object Number] consoleType('a'); // [object String]
consoleType(/\d/); // [object RegExp]