「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战」
-
判断方法一:
typeof类型检测注意:在这里
typeof只能检测出原始类型(null除外),对于引用类型统一返回objectconsole.log(typeof "1234") //++++++++++++++++++++ let p = 1234; console.log(typeof(p)); -
判断方法二:
instance of关系检测instanceof运算符用于检测构造函数constructor的prototype属性是否出现在某个实例对象的原型链上。function Car(make,model,year) { this.seeler = "yizhan"; this.make = make; this.model = model; this.year = year; } const auto = new Car('Honda','Accord',1998) console.log(auto instanceof Car); console.log(auto.make); console.log(auto.seeler); console.log(auto instanceof Object); /** *下面的解释更加明了 */ //instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上 function C() {} function D() {} var o = new C(); // 定义参数 o (object),原型于C() o instanceof C; //true,因为 Object.getPrototypeOf(o) === C.prototype // 获取构造函数原型链? console.log('C.prototype' + C.prototype); //获取参数 o 原型链上 object 的值 console.log('Object.getPrototypeof(o)' + Object.getPrototypeOf(o)); o instanceof Objectj; //false,因为 D.prototype 不在 o 的原型链上 o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true C.prototype instanceof Object // true,同上/** *进一步加深其他类型 */ var newStr = new String('定义的参数必须是以对象的形式声明的'); console.log(newStr); console.log(newStr instanceof String); -
判断方法三:
object.prototype.toString方法在这里首先要理解
call()、prototype为何物function detectType(type){ return function(obj){ return {}.toString.call(obj) === `[object ${type}]` } } const isArray = detectType("Array") const isFunc = detectType("Function") const isRegExp = detectType("RegExp") const isNumber = detectType("Number") const isString = detectType("String") console.log(isArray([1,2,3])); console.log(isArray("12345")); console.log(isString("12345")); console.log(isNumber(12345)); console.log(isString(12345)); // 检测并输出给定变量的类型 function getType(obj) { return {}.toString.call(obj) } console.log(getType("12345"));
灵魂总结:
不同的方法,各有用处!!(真正深挖需理解prototype原型链相关知识)
👆 👆 以上就是个人对【变量类型判断】的简单理解。
如果能够解开您的迷惑,不要忘记一键三连哟!!!
原型链知识请移步: 稍后添加😀
\