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

你可能感兴趣的文章
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>