分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

JS isArray、typeof、instanceof

发布时间:2023-09-06 01:39责任编辑:赖小花关键词:暂无标签

Array.isArray()

用来检验是不是数组

 ???????var a = [1,2,3] ???????console.log(typeof a); ??// object ???????console.log(Array.isArray(a)); ??// true

可以看出 typeof 并不能检验数组,虽然 Array.isArray() 可以检验数组,但是 IE8 都不兼容

 ???????var a = [1,2,3] ???????alert(Object.prototype.toString.call(a)) ?// ?[object Array]

这个方法可以兼容IE8 以及以下的浏览器

typeof

 ???????function foo(){} ???????console.log(typeof foo); ?// function ???????console.log(typeof null); // object ???????console.log(typeof undefined); ?// undefined ???????console.log(typeof ‘a‘); ???// ?string ???????console.log(typeof 1); ???// number

这里 null 是基本类型,不是一个对象,这个是 JS 的一个 bug。还有一个值得注意的地方:

console.log(undefined == null); ?// true

因为在 JS 中 undefined 是派生自 null 的

instanceof

 ???????function foo(){} ???????var a = new foo() ???????console.log(a instanceof foo); ??// true

instanceof 是根绝原型链来查找的,如果函数 foo 的显示原型对象在 a 对象的隐式原型链上,则返回 true,否则返回 false

绿色的就是对象 a 的原型链

JS isArray、typeof、instanceof

原文地址:https://www.cnblogs.com/lan1974/p/8360767.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved