0%

安全判断数据类型

之前在《高程》里面有一章节提到了安全判断数据类型,唯一弱点是没有改变 Object.prototype.toString() 没有被修改过。之前自己看的时候也是做了笔记的可是今天笔试的时候就想不到如何使用这个方法去实现了,编写下记录哈。

题目是判别简单类型(Number, String),数组,函数,对象,null,NaN(我也很好奇为啥算上 NaN(Number) 没有 undefined,那我自己写就考虑上哈)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function whichType(type){
if(Number.isNaN(type) === true){
return 'NaN'
}else if(Object.prototype.toString.call(type) === '[object Number]'){
return 'Number'
}else if(Object.prototype.toString.call(type) === '[object String]'){
return 'String'
}else if(Object.prototype.toString.call(type) === '[object Array]'){
return 'Array'
}else if(Object.prototype.toString.call(type) === '[object Function]'){
return 'Function'
}else if(Object.prototype.toString.call(type) === '[object null]'){
return 'null'
}else if(Object.prototype.toString.call(type) === '[object Undefined]'){
return 'undefined'
}else if(Object.prototype.toString.call(type) === '[object Object]'){
return 'Object'
}
return 'i dont know'
}

说实在代码惨不忍睹,改必须改

1
2
3
4
5
6
function whichType(type){
if(Number.isNaN(type) === true){
return 'NaN'
}
return Object.prototype.toString.call(type).match(/\w+/g)[1]
}

这样看起来是人写的了

恩恩就这样吧。

1
2
3
function whichType(type){
return Number.isNaN(type) === true ? 'NaN' : Object.prototype.toString.call(type).match(/\w+/g)[1]
}