JS变量类型判断

JS变量类型判断
1、typeof
返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、symbol、object、undefined、function等7种数据类型,但不能判断null、array等

typeof Symbol(); // symbol 有效
typeof ''; // string 有效
typeof 1; // number 有效
typeof true; //boolean 有效
typeof undefined; //undefined 有效
typeof new Function(); // function 有效
typeof null; //object 无效
typeof [] ; //object 无效
typeof {} ; //object 有效
typeof new Date(); //object 无效
typeof new RegExp(); //object 无效

2、instanceof
用来判断A是否为B的实例,A instanceof B, 返回 boolean 值。instanceof 用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,但它不能检测 null 和 undefined

'' instanceof String; //false
1 instanceof Number; //false
true instanceof Boolean; //false
new String('') instanceof String; //false
new Number(1) instanceof Number; //false
new Boolean(true) instanceof Boolean; //false
[] instanceof Array; //true
{} instanceof Object; //true
new Date() instanceof Date; //true
new RegExp() instanceof RegExp; //true
null instanceof Null; //报错
undefined instanceof Undefined; //报错


3、Object.prototype.toString.call()
一般数据类型都能够判断,最准确最常用的一种

Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]

猜你喜欢

转载自www.cnblogs.com/liushenga/p/12181291.html