博客
关于我
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/

你可能感兴趣的文章
python3 mysql8_Python MySQL8.0 错误:authentication plugin 'calling_sha2_password' is not supported....
查看>>
Python关键代码总览!从Zero到Hero必看的考点
查看>>
python3 robotframework+pycharm框架搭建
查看>>
Python3 shutil模块
查看>>
Python关于strftime函数详细解析 附实战代码
查看>>
Python3 tutorial day3
查看>>
python3 week4
查看>>
Python3 创建数组
查看>>
python3 套接字异常(a byte-like object is required not str)
查看>>
python3 实现用户三次输入错误记录黑名单并对该用户登录锁定-day1
查看>>
python3 文本变图片
查看>>
Python3 查看 com 组件的属性
查看>>
python3 案例分享--发邮件
查看>>
python3 模板库_Python3 标准库概览_Python教程_我爱模板网 - 提供下载各种免费建站资源,免费网站模板,免费网页特效,让你爱上建站!...
查看>>
Python3 求最大/小值及索引值 Numpy
查看>>
python3+django使用celery执行某些任务失败的解决方案
查看>>
Python3+Requests+Unittest实战系列【一】
查看>>
python3+requests+unittest实战系列【一】
查看>>
python3+requests+unittest实战系列【二】
查看>>
Python3+Requests+Unittest实战系列【二】
查看>>