在javascript使用typeof操作符并不能完全正确检测数据类型,比如:
typeof null; // 'object'
typeof []; // 'object'
typeof new Date(); // 'object'
typeof new RegExp(); // 'object'
但是,使用Object.prototype.toString
方法会返回当前数据的一个字符串类型说明,格式为[object Type]
,Type为数据类型。例如数组:[object Array]
,日期:[object Date]
,字符串:[object String]
等;以下是封装的共用方法:
function ValidType() {
const validObj = {};
const types = ['Number', 'String', 'Boolean', 'Object', 'Math', 'RegExp', 'Undefined', 'Null', 'Array', 'Function', 'Date']
for (var index = 0; index < types.length; index++) {
var type = types[index];
(function (type) {
validObj['is' + type] = function (value) {
return Object.prototype.toString.call(value) === `[object ${type}]`
}
})(type)
}
return valid
}
var valid = ValidType();
valid.isNull(null); // true 返回类型为[object Null]
valid.isArray([]); // true 返回类型为[object Array]
valid.isObject({}); // true 返回类型为[object Object]
valid.isDate(new Date()); // true 返回类型为[object Date]
当然,如果你学过ES6,你就应该知道使用let声明优化以上代码,let可以生成块级作用域,与闭包的作用一样,且代码更具可读性,易于理解;修改上面代码的for循环部分:
for (let index = 0; index < types.length; index++) {
var type = types[index];
valid['is' + type] = function (value) {
return Object.prototype.toString.call(value) === `[object ${type}]`
}
}