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

你可能感兴趣的文章
python list函数使用总结_史上最全的Python数据结构:列表和元组用法总结
查看>>
python locust 性能测试:locust参数-保证并发测试数据唯一性,循环取数据
查看>>
python locust 性能测试:locust安装和一些参数介绍
查看>>
python log
查看>>
python logging basicconfig_python之logging.basicConfig
查看>>
Python logging模块使用
查看>>
python logging模块学习
查看>>
python mac地址_python中MAC地址打包问题
查看>>
python manage.py syncdb Unknown command: 'syncdb'问题解决方法
查看>>
Python map() 函数 和 numpy mean()函数
查看>>
Python Matplotlib Box并排绘制两个数据集
查看>>
Python Matplotlib 中如何用 plt.savefig 存储图片
查看>>
Python matplotlib 中更换画布背景颜色
查看>>
Python进阶03 模块
查看>>
python matplotlib简单使用
查看>>
Python mock Patch os.environ 和返回值
查看>>
Python mock 修补另一个函数调用的函数
查看>>
python mqtt 客户端实现
查看>>
Python Multiprocessing - 将类方法应用于对象列表
查看>>
Python multiprocessing.Queue 与 multiprocessing.manager().Queue()
查看>>