JavaScript自定义数据类型判断函数
function judgeType(ele){ let res = typeof ele; if(res === "object"){ // 短路表达式,第一个成立则返回第二个的值,第一个不成立,则返回第一个的值 Object.prototype.toString.call(ele) === "[object Object]" && (res = "object"); Object.prototype.toString.call(ele) === "[object Array]" && (res = "array"); Object.prototype.toString.call(ele) === "[object Date]" && (res = "date"); Object.prototype.toString.call(ele) === "[object Null]" && (res = "null"); Object.prototype.toString.call(ele) === "[object RegExp]" && (res = "RegExp"); } return res; } // ----------一般数据类型--------- console.log(judgeType(23)); // number console.log(judgeType(false)); // boolean console.log(judgeType("23")); // string console.log(judgeType(undefined)); // undefined console.log(judgeType(NaN)); // number console.log(judgeType(function (){})); // function console.log("==============================="); // ---------- 对象类型数据--------- console.log(judgeType(null)); // object null console.log(judgeType({})); // object object console.log(judgeType([])); // object array console.log(judgeType(new Date())); // object date console.log(judgeType(new RegExp())); // object RegExp