首页 >

JavaScript中使用Object.prototype.toString判断是否为数组【javascript】

web前端|js教程JavaScript中使用Object.prototype.toString判断是否为数组【javascript】
JavaScript,Object.prototype.toString,判断是否为数组
web前端-js教程
为什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?这是和他们的toString解释方式有关系的。下面是ECMA中对Object.prototype.toString的解释:
.asp网上预约系统源码,vscode导入css,ubuntu用于,tomcat 图片丢失,ios 操作sqlite3,dz 棋牌插件,前端框架最常用的有哪些,车里有爬虫怎么处理好,php 脚本漏洞,付费seo哪家好,国外优秀的html5网站,php网页视频监控源码,手机怎么做简单表格模板图片lzw
Object.prototype.toString( )
签到打卡小程序源码,vscode怎样运行c程序,ubuntu进程stop,tomcat做app后端,python 爬虫403,php改文件夹名,贵州长沙seo优化企业,可以下单的商城网站源码,邪恶图类dedecms模板lzw
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)
其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object、获取的类名、]组合并返回。
ECMA中对Array有如下说明:
签到统计源码,ubuntu桌安装重启,tomcat浏览器访问白屏,图片爬虫旧版,php怎么解除后台密码,seo标准范围lzw
The [[Class]] property of the newly constructed object is set to “Array”.
因此我们用如下代码来检测数组:

function isArray(o) {   return Object.prototype.toString.call(o) === '[object Array]';  }  
这种方式既解决了instanceof存在的跨页面问题,也解决了属性检测方式所存在的问题,实在是一种妙招,一个很好的解决方案。
除此之外,这种解决办法也可以应用于判断Date,Function等类型的对象。

另外还有几个方法:

var arr = []; return arr instanceof Array;  
如果有其他好的方法不妨贴出来。


  • 暂无相关文章
  • Posted in 未分类