判断是否为数组

  如果你看过一些Javascript 的书,你应该会知道曾几何时判断是否为数组还是个问题;也会知道用instanceof 而不是typeof。再后来,还可以用Object.prototype.toString 来判断。直到ES5(ECMAScript 5.1)「2009」 给Array 加上了isArray 方法,现在大部分的库都使用Array.isArray 来判断了。

  关于Object.prototype.toString 处理逻辑,最近只在ES6 有更新。相对ES5 的处理多了不少逻辑,但是最终结果还是一样的。

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be ToObject(this value).
  4. Let isArray be IsArray(O).
  5. ReturnIfAbrupt(isArray).
  6. If isArray is true, let builtinTag be "Array".
  7. Else, if O is an exotic String object, let builtinTag be "String".
  8. Else, if O has an [[ParameterMap]] internal slot, let builtinTag be "Arguments".
  9. Else, if O has a [[Call]] internal method, let builtinTag be "Function".
  10. Else, if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
  11. Else, if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
  12. Else, if O has a [[NumberData]] internal slot, let builtinTag be "Number".
  13. Else, if O has a [[DateValue]] internal slot, let builtinTag be "Date".
  14. Else, if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
  15. Else, let builtinTag be "Object".
  16. Let tag be Get (O, @@toStringTag).
  17. ReturnIfAbrupt(tag).
  18. If Type(tag) is not String, let tag be builtinTag.
  19. Return the String that is the result of concatenating "[object ", tag, and "]".
您的浏览器已过时

要正常浏览本网站请升级您的浏览器。现在升级

×