根据要判断的数据对象,来选用合适的方法
1、原始数据类型
6种:number、string、boolean、undefined、null、symbol
一、typeof
let str = 'hello';
console.log(typeof str); // string
【特殊!!】null的类型判断,不能使用typeof、instanceof、constructor
let s = null; console.log(typeof s) //Object
下面是两种判断是否为null类型的方法:
console.log(s === null)
console.log(Object.prototype.toString.call(s) === '[object Null]');
2、对于部分引用数据类型:object、function,也可以使用typeof
let obj = {
}
console.log(typeof obj); // object
function func(){
return 'this is a function';
}
console.log(typeof func); // function
3、对于其他的引用数据类型:Array、Date、RegExp
typeof有局限性:对于第3种情况中列举的部分引用数据类型,使用typeof只能显示object,而不会显示具体的Array。【不能用来区分:一种对象类型和另一种对象类型】
let arr = [1,2,3,4];
console.log(typeof arr); // object,此时就不能typeof了
二、instanceof
let arr = [1,2,3,4];
console.log(arr instanceof Array); // true
instanceof 运算符要求其左边的运算数是一个对象,右边的运算数是对象类的名字或构造函数。如果 object 是 class 或构造函数的实例,则 instanceof 运算符返回 true。如果 object 不是指定类或函数的实例,或者 object 为 null,则返回 false。
let str = 'hello';
console.log(str instanceof String); // false
三、constructor属性
let arr = [1,2,3,4];
console.log(arr.constructor); // ƒ Array() { [native code] },引用了初始化该对象的构造函数
console.log(arr.constructor === Array); // true
let date = new Date();
console.log(typeof date); // object
console.log(date.constructor); // Date
let reg = new RegExp("/^/d*$/") ;
console.log(typeof reg); // object
console.log(reg.constructor); // RegExp
补充:到底什么是JS原型
原型对象中的constructor属性,指向构造函数
【思考】:第三、四种方法之间,是不是有什么联系?
arr是原型对象还是实例对象?
4、对于跨框架
下面这段话大家自行领悟一下,我也不是很懂
四、Object.prototype.toString()
参考:JavaScript 中 call()、apply()、bind() 的用法
call()是用来改变this指向的,同理可以使用apply、bind
【注意】:bind返回的是一个新的函数,需要再调用一次
let arr = [1,2,3,4];
console.log(Object.prototype.toString.call(arr)); // [object Array]
console.log(Object.prototype.toString.call(arr) === "[object Array]");
console.log(Object.prototype.toString.apply(arr));
console.log(Object.prototype.toString.apply(arr) === "[object Array]");
console.log(Object.prototype.toString.bind(arr)); // ƒ toString() { [native code] }
console.log(Object.prototype.toString.bind(arr)()); //[object Array]
console.log(Object.prototype.toString.bind(arr)() === "[object Array]");
最后
注意:为了描述直观,文中出现了一个变量多次let声明的情况,在代码中,用let声明的变量只能声明一次,否则会报错,但后续可以修改变量值