变量数据类型及检测: typeof,intanceof ,constructor,tostring

作用:使用typeof操作符来检测变量的数据类型
实例:
typeof "John"                // 返回 string 
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean
typeof [1,2,3,4]             // 返回 object
typeof {name:'John', age:34} // 返回 object


null
typeof null 返回object

null是一个只有一个值的特殊类型,表示一个空对象引用


undefined
typeof undefined返回undefined
undefined是一个没有设置值的变量


undefined和null的区别
null 和 undefined 的值相等,但类型不等:

 


typeof undefined             // undefined
typeof null                  // object
null === undefined           // false

 

null == undefined            // true

 

 

instanceof

可通过 instanceof 操作符来判断对象的具体类型

instanceof适用于检测对象,它是基于原型链运作的。对基本数据类型检测不起作用,因为基本数据没有原型链。

(1)检测内部对象

arr = [1,2,3];
if(arr instanceof Array){
    document.write("arr 是一个数组");
} else {
    document.write("arr 不是一个数组");
}

 

(2)检测任意类型对象

// 比如直接原型关系
function Animal () {};
var a =  new Animal();
a instanceof Animal; // => true
 


constructor属性:返回一个创建了该对象原型的函数引用;
constructor不适合判断变量类型,因为它是一个属性,容易伪造
constructor只能用于检测对象,对基本类型调用会抛出异常。
null.constructor; // => TypeError
undefined.constructor; // => TypeError


toString:最简单的数据类型检测方法,但是因为toString属性定义在Object.prototype上
,所以所有的对象都有toString方法,默认情况下,都会返回[object object];但可以通过
.call()方法来解决
Object.prototype.toString.call([]); // => [object Array]
Object.prototype.toString.call({}); // => [object Object]
Object.prototype.toString.call(''); // => [object String]
Object.prototype.toString.call(new Date()); // => [object Date]
Object.prototype.toString.call(1); // => [object Number]
Object.prototype.toString.call(function () {}); // => [object Function]
Object.prototype.toString.call(/test/i); // => [object RegExp]
Object.prototype.toString.call(true); // => [object Boolean]
Object.prototype.toString.call(null); // => [object Null]
Object.prototype.toString.call(); // => [object Undefined]

  • typeof只能检测基本数据类型,对于null还有Bug;
  • instanceof适用于检测对象,它是基于原型链运作的;
  • constructor指向的是最初创建者,而且容易伪造,不适合做类型判断;
  • toString适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断;
  • 基于引用判等的类型检查都有跨窗口问题,比如instanceofconstructor

总之,如果你要判断的是基本数据类型或JavaScript内置对象,使用toString; 如果要判断的是自定义类型,请使用instanceof

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值