javascript检验数据类型的方法

typeof

typeof返回数据类型:number、string、boolean、symbel、undefined、function、object。引用数据中的数组、日期、正则都会被返回object。并且对于简单数据类型的null也会返回object。

const num = 10
const str = 'string'
const bol = true
const Undefined = undefined
const fn = () => { }
const obj = new Object()
const date = new Date()
const arr = []
const brr = /^[a-z]^/
const Null = null

console.log(typeof num);
console.log(typeof str);
console.log(typeof bol);
console.log(typeof Undefined);
console.log(typeof fn);
console.log(typeof obj);
console.log(typeof date);
console.log(typeof arr);
console.log(typeof brr);
console.log(typeof Null);

constructor

constructor是原型prototype中的一个属性,当函数被定义时,js会为函数添加原型prototype,并且这个prototype中construor属性指向函数引用。但是constructor无法识别null和undefined,如果调用的话会报错。

console.log(num.constructor);
console.log(str.constructor);
console.log(bol.constructor);
console.log(fn.constructor);
console.log(obj.constructor);
console.log(date.constructor);
console.log(arr.constructor);
console.log(brr.constructor);
console.log(Null.constructor);
console.log(Undefined.constructor);



Object.prototype.toString.call()

可以返回所有的数据类型(博主暂时了解的),toString是Object的原型方法,其他类型作为Object的实例都重写了toString方法,所以需要用call去调用Object上原型toString方法

console.log(Object.prototype.toString.call(num));
console.log(Object.prototype.toString.call(str));
console.log(Object.prototype.toString.call(bol));
console.log(Object.prototype.toString.call(fn));
console.log(Object.prototype.toString.call(obj));
console.log(Object.prototype.toString.call(date));
console.log(Object.prototype.toString.call(arr));
console.log(Object.prototype.toString.call(brr));
console.log(Object.prototype.toString.call(Null));
console.log(Object.prototype.toString.call(Undefined));

instanceof

instanceof检测的是原型,A instanceof B检测的是B.prototype是否出现在A的原型链上,所以instanceof只能判断两个对象是否属于实例关系,而不能判断一个对象实例具体属于那种类型

let array = [1, 2, 34, 5];
let obj = {}
console.log(array instanceof Array); //true
console.log(Array instanceof Object); //true
console.log(array instanceof Object); //true
console.log(obj instanceof Array); //false
posted @ 2021-08-04 17:02  卿六  阅读(89)  评论(0编辑  收藏  举报