判断是否为数组
如果你看过一些Javascript 的书,你应该会知道曾几何时判断是否为数组还是个问题;也会知道用instanceof
而不是typeof
。再后来,还可以用Object.prototype.toString
来判断。直到ES5(ECMAScript 5.1)「2009」 给Array 加上了isArray 方法,现在大部分的库都使用Array.isArray
来判断了。
关于Object.prototype.toString
处理逻辑,最近只在ES6 有更新。相对ES5 的处理多了不少逻辑,但是最终结果还是一样的。
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be ToObject(this value).
- Let isArray be IsArray(O).
- ReturnIfAbrupt(isArray).
- If isArray is true, let builtinTag be "Array".
- Else, if O is an exotic String object, let builtinTag be "String".
- Else, if O has an [[ParameterMap]] internal slot, let builtinTag be "Arguments".
- Else, if O has a [[Call]] internal method, let builtinTag be "Function".
- Else, if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
- Else, if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
- Else, if O has a [[NumberData]] internal slot, let builtinTag be "Number".
- Else, if O has a [[DateValue]] internal slot, let builtinTag be "Date".
- Else, if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
- Else, let builtinTag be "Object".
- Let tag be Get (O, @@toStringTag).
- ReturnIfAbrupt(tag).
- If Type(tag) is not String, let tag be builtinTag.
- Return the String that is the result of concatenating "[object ", tag, and "]".