daily-interview / fe-interview

:smiley: 每日一道经典前端面试题,一起共同成长。
https://blog.csdn.net/u010494753
MIT License
172 stars 22 forks source link

如何只用两行代码实现判断js中所有数据类型 #59

Open artdong opened 4 years ago

artdong commented 4 years ago

判断js数据类型最简方法

let _toString = Object.prototype.toString;

function getType (value) {return _toString.call(value).slice(8, -1)}
getType(); // "Undefined"
getType(''); // "String"
getType(1); // "Number"
getType(1n); // "BigInt"
getType(Symbol('uid')); // "Symbol"
getType(true); //"Boolean"
getType([]); //"Array"
getType({}); //"Object"
getType(null); //"Null"
getType(function(){}); //"Function"