更新时间:2019年07月26日 11时16分51秒 来源:黑马程序员论坛
今天跟大家分享一个获取精准的数据类型的方法。 废话不多说。直接上代码↓↓↓ 第一个参数就是需要获取数据类型的对象 第二个参数是进行判断该对象是不是指定的数据类型(默认没有) 当有第二个参数的时候,则就会进行返回布尔值 true | false ,没有就返回该数据的类型 /** * 获取数据类型 * */ function getType (obj, str) { let type = '' if (Object.prototype.toString.call(obj) === '[object Array]') { type = 'array' } else if (Object.prototype.toString.call(obj) === '[object Boolean]') { type = 'boolean' } else if (Object.prototype.toString.call(obj) === '[object Number]') { type = 'number' } else if (obj instanceof HTMLElement) { type = 'dom' } else if (obj instanceof Map) { type = 'map' } else if (typeof (obj) == 'object' && Object.prototype.toString.call(obj).toLowerCase() == '[object object]' && !obj.length) { type = 'json' } else { type = typeof (obj) } return str ? type === str : type } --------------------- 相关阅读 |