js判断类型的主要方法有:typeof, instanceof, constructor, prototype
方式一之--typeof
- 返回值:字符串(
undefined,object,boolean,number,bigint,string,symbol,function) - 可判断的类型:
String, Boolean, Number, bigInt, Undefined, Function, Symbol - 不可判断的类型:
Null, Object, Array - 注:null返回object, NaN的值也会返回number
引申:如何判断Array
拓展之--实现isNumber(主要是排除NaN的情况)
function isNumber(obj){
return typeof obj==='number' && !isNaN(obj)
}
function isNumber(obj){
return Object.prototype.toString.call(obj)==='number' && !isNaN(obj)
}
方式二之--instanceof
- 用于检测构造函数的
prototype属性是否出现在某个实例对象的原型链上,网上这篇关于原型与原型链文章写的挺清晰易懂的
语法: object instanceof constructor (object为实例对象,constructor为构造函数)
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
方式三之--constructor
constructor 属性返回 Object 的构造函数(用于创建实例对象)。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。
所有对象(使用 Object.create(null) 创建的对象除外)都将具有 constructor 属性。在没有显式使用构造函数的情况下,创建的对象(例如对象和数组文本)将具有 constructor 属性,这个属性指向该对象的基本对象构造函数类型。
const o = {}
o.constructor === Object // true
const o = new Object
o.constructor === Object // true
const a = []
a.constructor === Array // true
const a = new Array
a.constructor === Array // true
const n = new Number(3)
n.constructor === Number // true
注意: constructor 在类继承时会出错
eg:
function A(){};
function B(){};
A.prototype = new B(); //A继承自B
var aObj = new A();
alert(aobj.constructor === B) -----------> true;
alert(aobj.constructor === A) -----------> false;
而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true:
alert(aobj instanceof B) ----------------> true;
alert(aobj instanceof B) ----------------> true;
解决construtor的问题通常是让对象的constructor手动指向自己:
aobj.constructor = A; //将自己的类赋值给对象的constructor属性
alert(aobj.constructor === A) -----------> true;
alert(aobj.constructor === B) -----------> false; //基类不会报true了;
方法四之--Object.prototype.toString.call
var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="22";};
alert(Object.prototype.toString.call(a) === '[object String]') -------> true;
alert(Object.prototype.toString.call(b) === '[object Number]') -------> true;
alert(Object.prototype.toString.call(c) === '[object Array]') -------> true;
alert(Object.prototype.toString.call(d) === '[object Date]') -------> true;
alert(Object.prototype.toString.call(e) === '[object Function]') -------> true;
alert(Object.prototype.toString.call(f) === '[object Function]') -------> true;