衡阳市建设学校官方网站,哪个公司做网站建设好,施工企业资料员,百度关键词竞价排名检测数据类型的4种方法typeofinstanceofconstructor{}.toString.call()
检测数据类型的4种方法
typeof
定义
用来检测数据类型的运算符 返回一个字符串#xff0c;表示操作值的数据类型(7种) number#xff0c;string#xff0c;boolean#xff0c;object#xff0c;u…检测数据类型的4种方法typeofinstanceofconstructor{}.toString.call()
检测数据类型的4种方法
typeof
定义
用来检测数据类型的运算符 返回一个字符串表示操作值的数据类型(7种) numberstringbooleanobjectundefinedsymbolfunction 使用方法1typeof(value) 使用方法2typeof value
typeof(null)
注意 typeof(null) object (这是浏览器遗留的BUG所有的值都以二进制编码存储浏览器中把前三位000的当作对象而null的二进制前三位是000所以识别为对象但他不是对象而是空指针对象是基本类型值)
typeof(undefined)
typeof undefined ‘undefined’ 注意typeof 未声明的变量返回 undefined
typeof a;//undefined
typeof typeof a;//stringinstanceof
定义用来检测某个实例是否属于这个类返回布尔值 》 当前类的原型只要出现在实例的原型链上就返回 true 使用方法实例 instanceof 类 优点弥补 typeof 无法细分对象类型的特点 局限性
只能检测对象数据类型
a instanceod Object;//false
// 例如
ImageryProvider instanceof Cesium.ImageryProvider构造函数创建的基本类型可以检测
var a new String(a)
a instanceof Object万物皆对象数组对象正则都是 Object的实例
constructor
定义判断当前的实例的 constructor 的属性值返回函数 》 利用他的实例的构造函数检测 》 一般实例.constructor 类.prototype.constructor 使用方法实例.constructor 类 优点能够检测所有的数据类型包括自定义类
function Person (){...}
new Person().constructor; //ƒ Person (){}缺点JS中的 constructor 是不被保护的可以重定向
Array.constructor;// f Array () {}
Array.constructor 1;// 1{}.toString.call() 推荐
定义对象原型上的toString方法能返回当前实例所属类的信息 》返回字符串 使用方法Object.prototype.toString.call(被检测的实例) 优点基本能基础所有的数据类型
console.log({}.toString.call(1));// [object Number]
console.log({}.toString.call(a));// [object String]
console.log({}.toString.call(true));// [object Boolean]
console.log({}.toString.call(Symbol.for(a)));// [object Symbol]
console.log({}.toString.call(undefined));// [object Undefined]
console.log({}.toString.call(null));// [object Null]
console.log({}.toString.call({}));// [object Object]
console.log({}.toString.call([]));// [object Array]
console.log({}.toString.call(/a/g));// [object RegExp]局限性自定义类都返回 [object Object]
function Test(a){this.a 1}
let test new Test(1)
console.log({}.toString.call(test))//[object Object]