1、关于typeof
typeof(item):返回item的数据类型
js有基本数据类型number,string,null,undefined,boolean,symbol等,其余为引用类型object的变形
由下示例可以看出:
typeof():可以检测出:string,function,undefined,number,boolean等类型
但不可以检测:null,Array,Date,RegExp等对象的类型
代码示例:
<script>
var str = '123',
arr = [],
fun = function() {},
n = null,
un = undefined,
number = 123,
flag = true,
date = new Date(),
reg = new RegExp();
console.log(typeof(str)); //string
console.log(typeof(arr)); //object
console.log(typeof(fun)); //function
console.log(typeof(n)); //object
console.log(typeof(un)); //undefined
console.log(typeof(number)); //number
console.log(typeof(flag)); //boolean
console.log(typeof(date)); //object
console.log(typeof(reg)); //object
</script>
2、关于instanceof
A instanceof B:判断A是否是B的实例,返回boolean类型;
原理:检查一个对象A的原型链中是否有构造函数B的prototype属性
代码示例:
<script>
console.log(arr instanceof Array); //true
console.log(str instanceof String); //false
str = new String(123);
console.log(str instanceof String); //true
console.log(date instanceof Date); //true
console.log(reg instanceof RegExp); //true
</script>
3、关于Object.prototype.toString.call()
Object上的toString()返回当前this的详细信息
代码示例:
<script>
console.log(Object.prototype.toString.call(str)); //[object String]
console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(Object.prototype.toString.call(n)); //[object Null]
console.log(Object.prototype.toString.call(un)); //[object Undefined]
console.log(Object.prototype.toString.call(number)); //[object Number]
console.log(Object.prototype.toString.call(flag)); //[object Boolean]
console.log(Object.prototype.toString.call(date)); //[object Date]
console.log(Object.prototype.toString.call(reg)); //[object RegExp]
let type = Object.prototype.toString.call(str);
type = type.slice(8, type.length - 1);
console.log(type);//String
</script>