typeof只能判断基本类型 :string
,number
,boolean
, undefined
,object
typeof不能判断数组和对象
Object.prototype.toString.call()可以判断:
"Array", "Function", "Object", "RegExp", "Date"
const typeCheck = (obj) => { const typeStr = Object.prototype.toString.call(obj); return typeStr.toLowerCase().slice(8, typeStr.length - 1); }; console.log(typeCheck("str")); console.log(typeCheck(1)); console.log(typeCheck(() => null)); console.log(typeCheck({a: 1})); console.log(typeCheck([1, 2, 3])); console.log(typeCheck(new Set([1,2,3])));