JavaScript 中怎样判断一个对象是不是数组?

April 2, 2024

直接判断是否为数组

静态方法 Array.isArray() 可以判断传入的值是否为数组。

  1. MDN 文档,Array.isArray(),无日期。2024 年 4 月 2 日查阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

既然这么简单,为什么还会有这个问题?

我曾经尝试用“这个值是否可迭代”来代替数组判断,这种写法有隐患: 字符串也可以逐字符迭代,所以它同样会通过检查,得到意外的结果。

  1. Tomas Kulich(2015 年 9 月 12 日)在 Stack Overflow 的回答中解释了如何检查可迭代性,并提到这里讨论的 for..of 来自 ES6。如果 obj 是字符串,检查也会返回 true,因为字符串可以逐字符迭代。迭代协议;原回答。

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-04-02). JavaScript 中怎样判断一个对象是不是数组?. https://caiborui.com/blog/2024-04-02-en-how-to-properly-check-whether-is-array-zhtrans

@misc{borui2024-68dea474,
  author = {borui},
  title = {{JavaScript 中怎样判断一个对象是不是数组?}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-04-02-en-how-to-properly-check-whether-is-array-zhtrans}
}