Object.prototype.toString.call(检测数据类型最佳方案)
调用Object原型上的toString()方法,并且通过call改变this指向。返回字符串 ,我们看看八种数据类型分别返回的结果
function checkType(param) { return Object.prototype.toString.call(param) } console.log(checkType(123)) //[object Number] console.log(checkType("123")) //[object String] console.log(checkType(true)) //[object Boolean] console.log(checkType({ a: 123 })) //[object Object] console.log(checkType(() => {})) //[object Function] console.log(Symbol(1)) //Symbol(1) console.log(null) //null console.log(undefined) //undefined
我们再对上述函数进行一下处理
function checkType(param) { return Object.prototype.toString.call(param).slice(8, -1).toLowerCase() } console.log(checkType(1)) // number console.log(checkType("123")) //string console.log(checkType(true)) //boolean console.log(checkType({ a: 123 })) //object console.log(checkType(() => {})) //function console.log(Symbol(1)) //symbol console.log(null) //null console.log(undefined) //undefined
链接:https://juejin.cn/post/6893856813247266823
来源:掘金