第9天 写一个判断数据类型的方法
Activity
qqdnnd commentedon May 16, 2019
myprelude commentedon Jun 13, 2019
不能判读 数组 和 对象
Damon99999 commentedon Jun 18, 2019
MartinsYong commentedon Jun 25, 2019
bWhirring commentedon Jul 3, 2019
Konata9 commentedon Jul 5, 2019
typeof
只能判断基本类型string
,number
,boolean
,undefined
,object
null
会被判断成object
比较全面的是使用
Object.prototype.toString
方法,只需要对返回值进行字符串分割即可Vi-jay commentedon Jul 25, 2019
NeverLoseYourWay commentedon Aug 9, 2019
15190408121 commentedon Aug 25, 2019
function types (obj) {
return Object.prototype.toString.call(obj).replace(/[object\s|]/g, '');
}
console.log(type({}))
console.log(type(1))
console.log(type([]))
fanqingyun commentedon Sep 2, 2019
function getType(target){
let rs = Object.prototype.toString.call(target).split(' ')
return rs[1].substr(0, rs[1].length-1)
}
J1nvey commentedon Sep 6, 2019
careteenL commentedon Sep 6, 2019
typeof不足
❌众所周知原生
typeof
有很多不足如下所示:✅我们期望能返回下面:
实现并封装
将功能封装在@careteen/type,可前往查看支持类型以及测试用例。
下面写法支持
xcLtw commentedon Sep 11, 2019
有几个小问题
Object.prototype.toString
这里的toString
和toString()
的区别是啥,toString()
是原生对象提供的方法的话,如何描述toString
呢([]).toString //ƒ toString() { [native code] }
在浏览器控制台输入的这个返回,表示toString
被理解成一个函数,里面的native code又表示什么呢,是代表了原生Object
上的部分还是重写之后的(10).toString(2) // '1010'
不同的数据类型带有的toString()
是有区别的,特别是数字型的可以做进位转换40 remaining items