我最常用的方式:
1 2 3 | function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | let num = 1; console.log(getType(num)); // "Number" let str = "Hello World"; console.log(getType(str)); // "String" let arr = [1, 2]; console.log(getType(arr)); // "Array" let obj = { name: "sand" }; console.log(getType(obj)); // "Object" let func = function() {}; console.log(getType(func)); // "Function" let n = null; console.log(getType(n)); // "Null" let u = undefined; console.log(getType(u)); // "Undefined" |
声明: 本文采用 BY-NC-SA 协议进行授权 | WEB开发分享
转载请注明转自《如何判断js的类型?》