typeof
-
检测方法
主要用于检测基本类型.
-
缺点: 无法区分 引用类型
引用类型:object。里面包含的 function、Array、Date。
-
优点 方便快捷 代码量少 区分基本类型正常
基本类型:Number、String、Boolean、Null、undefined、object、symbol、bigInt。
typeof(123) //number
typeof('123')// string
typeof({})//object
typeof([])//object
typeof(new Date) //object
instanceof
- 主要用于检测引用类型
查找方在对应的值原形链上有.prototype有无对应的,返回true;否则返回false
-
缺点
检测基本数据类型较为麻烦 检测前必须要实力对应的数据类型,否则检测不准确
优点:
检测引用类型准确
console.log(123 instanceof Object); //false
console.log(new Number(123) instanceof Number); //true
console.log(new String('123') instanceof String); //true
console.log('123' instanceof String); //false
console.log([] instanceof Array); //true
console.log({} instanceof Object); //true
Object.prototype.toString.call
- 缺点
代码量过长 - 优点
检测类型准确,无论是基本类型还是引用引用类型都可检测
console.log(Object.prototype.toString.call({})); //[object Object]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call(false)); //[object Boolean]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call('1123')); //[object String]
console.log(Object.prototype.toString.call(Symbol()));//[object Symbol]
console.log(Object.prototype.toString.call(new Date)); //[object Date]
//..... 对此方法来封装 额这一坨优点像 下面我们来简便代码
function isType (data) {
if (data === '') return '';
switch (Object.prototype.toString.call(data))
{
case '[object Object]':
return 'Object';
case '[object Number]':
return 'Number';
case '[object Array]':
return 'Array';
case '[object Boolean]':
return 'Boolean';
case '[object Null]':
return 'Null';
case '[object Undefined]':
return 'Undefined';
case '[object String]':
return 'String';
case '[object Symbol]':
return 'Symbol';
case '[object Date]':
return 'Date';
case '[object BigInt]':
return 'BigInt';
case '[object Function]':
return 'Function';
}
}
//第二种方法最终版
function isType (data) {
if (data === '') return '';
let istypeArray = ['Object', 'Number', 'Array', 'Boolean', 'Null', 'Undefined', 'String', 'Symbol', 'Date', 'BigInt', 'Function'];
let is = Object.prototype.toString.call(data);
for (let i = 0; i < istypeArray.length; i++)
{
if (is.includes(istypeArray[i])) return istypeArray[i]
}
}