Skip to content

Instantly share code, notes, and snippets.

@hereisfun
Created April 24, 2017 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hereisfun/b040fff4667b0a3aa7966b4e5dc21d4a to your computer and use it in GitHub Desktop.
Save hereisfun/b040fff4667b0a3aa7966b4e5dc21d4a to your computer and use it in GitHub Desktop.
js类型检测,包括ES5/6
//从ES5.1开始,undefined和null能返回正确的[object Undefined] [object Null]
//且ES6多了更多类型,既然难易枚举完毕,干脆全都用Object.prototype.toString.call()
//基于ES5.1以下的
function type(data) {
// 对于null,typeof会返回object
if(data === null) {
return 'null';
}else if(data === undefined){
return 'undefined';
}else if (typeof data !== 'object' && typeof data !== 'function'){
//基本类型能被typeof正确判断
return typeof data
}else{
//其它依赖Object.prototype.toString.call()输出的 [object Obejct]等符号标识
// var typeList = ['Number', 'String', 'Boolean', 'RegExp', 'Object', 'Function', 'Array', 'Date', 'Error'];
// var type = {};
// typeList.forEach(function(data) {
// type[`[object ${data}]`] = data.toLowerCase();
// });
// return type[Object.prototype.toString.call(data)];
var sign = Object.prototype.toString.call(data);
var realType = sign.split('').slice(8,-1).join('').toLowerCase();
return realType;
}
}
var dump = [
1,
'asd',
true,
undefined,
null,
new Date(),
/\s/,
new Function(),
String('asd'),
Number('123'),
Boolean('1'),
new Error()
]
dump.forEach(function(data) {
console.log(type(data));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment