博客
关于我
js 判断一个对象是否是数组
阅读量:716 次
发布时间:2019-03-21

本文共 1092 字,大约阅读时间需要 3 分钟。

如何确定变量是否为数组?以下是几种常用的方法,并附带示例说明:

方法一:arr instanceof Array

这种方法直接使用 JavaScript 的类型判断功能,简单且直观。

if (arr instanceof Array) {  // 处理是数组的情况}

此方法的缺点是,在某些框架中可能无法正常工作,比如避免直接使用内置 RTL(例如在某些模块化框架中可能导致错误)。

方法二:Array.isArray(arr)

这种方法通过调用 JavaScript 的内置函数 Array.isArray 来判断数组。这种方法更为可靠,且在所有环境中都适用。

if (Array.isArray(arr)) {  // 处理是数组的情况}

这种方法不仅简洁,而且不容易引发安全问题,深受开发者推荐。

方法三:Object.prototype.toString.call(arr) === "[object Array]"

这是最通用的方法,适用于所有情况。虽然稍微复杂一些,但能有效避免跨框架问题。

if (Object.prototype.toString.call(arr) === "[object Array]") {  // 处理是数组的情况}

这种方法通常用于需要更严格检查或防止潜在错误(例如在不确定环境下)。

说明

以下是一些通过 Object.prototype.toString.call() 方法得到的常见结果示例:

  • Object.prototype.toString.call(123) —— "[object Number]"
  • Object.prototype.toString.call('123') —— "[object String]"
  • Object.prototype.toString.call(undefined) —— "[object Undefined]"
  • Object.prototype.toString.call(true) —— "[object Boolean]"
  • Object.prototype.toString.call({}) —— "[object Object]"
  • Object.prototype.toString.call([]) —— "[object Array]"
  • Object.prototype.toString.call(function() {}) —— "[object Function]"

这些方法可以帮助你准确判断变量的类型。根据需要选择最合适的方法,结合代码环境和可读性因素进行选择。

转载地址:http://ystrz.baihongyu.com/

你可能感兴趣的文章
nginx+tomcat+memcached
查看>>
nginx+tomcat单个域名及多个域名配置
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx: [error] open() “/usr/local/nginx/logs/nginx.pid“ failed (2: No such file or directory)
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
nginxWebUI runCmd RCE漏洞复现
查看>>
nginx_rtmp
查看>>
Vue中向js中传递参数并在js中定义对象并转换参数
查看>>
Nginx、HAProxy、LVS
查看>>
nginx一些重要配置说明
查看>>