js中手写实现 万能的数据类型判断 你知道吗

210 阅读1分钟

const typeOf = (obj) => { let res = Object.prototype.toString.call(obj).split(' ')[1] res = res.substring(0, res.length - 1).toLowerCase()

// 使用Object.prototype.toString.call()方法的到的都是一个字符串 [object 类型 ] 所以使用 // 字符串的方法split()字符串分割成数组并获取下标为一的那一项。例如 string ] numblr ] ... return res // 由于后面的截取后的对象表现为string ] 需要再次截取掉后面的 ] substring(0,res.length-1) // 最后不要忘记重新赋值 }

const res = typeOf(0) console.log(res)