数据类型检测的方式有哪些?

1)typeof
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'
其中数组、对象、null 都会被判断为 object,其他判断都正确。
2)instanceof
instanceof 可以正确判断对象的类型,其内部运行机制是判断在其
原型链中能否找到该类型的原型。
console.log(2 instanceof Number); // false
console.og(true instanceof Boolean); // false
console.log('str' instanceof String); // false
console.log([] instanceof Array); // true
console.log(function()) instanceof Function); // true
console.log( instanceof Object); // true
可以看到,instanceof 只能正确判断引用数据类型,而不能判断基
本数据类型。instanceof 运算符可以用来测试一个对象在其原型链
中是否存在一个构造函数的 prototype 属性。
3) constructor
console.log((2).constructor === Number); // true
console.log((true).constructor === Boolean); // true
console.log(('str").constructor == String); // true
console.log(([]).constructor === Array); // true
console.log((function() }).constructor === Function); // true
console.log((0).constructor === Object); // true
constructor 有两个作用,一是判断数据的类型,二是对象实例通过
constrcutor 对象访问它的构造函数。需要注意,如果创建一个对象
来改变它的原型,constructor 就不能用来判断数据类型了:
function Fn(){};
Fn.prototype = new Array();
var f new Fn();
console.log(f.constructor===Fn);// false
console.log(f.constructor===Array); // true
4)Object.prototype.toString.call()
Object.prototype.toString.call() 使用 Object 对象的原型方法
toString 来判断数据类型:
var a = Objectprototype.toString;
console.log(a.cal1(2));
console.log(a.cal1(true));
console.log(a.cal1("str"));
console.log(a.cal1([]));
console.log(a.call(function()0)));
console.log(a.cal1({}));
console.log(a.cal1(undefined));
console.log(a.call(null));
同样是检测对象 obj 调用 toString 方法,obj.toString()的结果和
Object.prototype.toString.call(obj)的结果不一样,这是为什
么?
这是因为 toString 是 Object 的原型方法,而 Array、function 等类 型作为 Object 的实例,都重写了 toString 方法。不同的对象类型调用 toString 方法时,根据原型链的知识,调用的是对应的重写之后的 toString 方法(function 类型返回内容为函数体的字符串,Array 类型返回元素组成的字符串…),而不会去调用 Object 上原型 toString 方法(返回对象的具体类型),所以采用 obj.toString() 不能得到其对象类型,只能将 obj 转换为字符串类型;因此,在想要
得到对象的具体类型时,应该调用 Object 原型上的 toString 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚时之秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值