Javascript类型检测

1.typeof

typeof 适合基本类型及function检测,遇到null失效。

10余年的巩义网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都营销网站建设的优势是能够根据用户设备显示端的尺寸不同,自动调整巩义建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“巩义网站设计”,“巩义网站推广”以来,每个客户项目都认真落实执行。

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类型检测
网页链接:https://www.cdcxhl.com/article12/pididc.html

成都网站建设公司_创新互联,为您提供做网站微信小程序软件开发网站设计公司动态网站外贸建站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设公司