Javascript类型检测
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Javascript类型检测,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1747字,纯文字阅读大概需要3分钟。
内容图文
1.typeof
typeof 适合基本类型及function检测,遇到null失效。
typeof 100; // "number"
typeof true; // "boolean"
typeof fun(); // "function"
typeof NaN; // "number"
typeof undefined; // "undefined"
typeof null; // "object"
typeof new Object(); // "object"
typeof [1,2]; // "object"
2.instanceof
instanceof一般用于对象类型的判断,是基于原型链的判断。
//obj instanceof Object
[1,2] instanceof Array === true
new Object() instanceof Array === false
function Student(){}
function Teacher(){}
var s = new Student()
console.log(s instanceof Student) // true
console.log(s instanceof Teacher) // false
Student.prototype = new Teacher()
var s2 = new Student()
console.log(s2 instanceof Student) // true
console.log(s2 instanceof Teacher) // true
PS:适合自定义对象,也可以用来检测原生对象。不同window或iframe间的对象类型检测不能用instanceof。
3.Object.prototype.toString.apply()
通过{}.toString拿到,适合内置对象和基本类型,遇到null和undefined失效(IE678返回[object Object])。
Object.prototype.toString.apply([]) === "[object Array]"
Object.prototype.toString.apply(function(){}) === "[object Function]"
Object.prototype.toString.apply(null) === "[object Null]" // IE6/7/8返回"[object Object]"
Object.prototype.toString.apply(undefined) === "[object Undefined]"
Object.prototype.toString.apply(123) === "[object Number]"
Object.prototype.toString.apply('123') === "[object String]"
Object.prototype.toString.apply(true) === "[object Boolean]"
console.log(Object.prototype.toString.apply(new Object())) //[object Object]
function Student(){}
var s = new Student()
console.log(Object.prototype.toString.apply(s)) //[object Object]
console.log(Object.prototype.toString.apply(window)) // [object Window]
console.log(Object.prototype.toString.apply(new Date())) //[object Date]
内容总结
以上是互联网集市为您收集整理的Javascript类型检测全部内容,希望文章能够帮你解决Javascript类型检测所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。