对象原型上的 toString().call() 如何获取数组的类型
How toString().call() on object prototype is fetching the type of Array
我正在查看代码以确定一个对象是否是一个数组,我遇到了 this answer。
代码运行良好,但我无法理解它是如何与 [object Array]
进行比较的
我试图获取 typeof Array
,但出现错误。所以我对这段代码感到困惑
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
我很想知道对对象的 toString.call( _ON_AN_ARRAY_ )
方法调用如何正确获取数组对象的类型。
从技术上讲,数组是一个对象,所以当您执行 typeof arrayVar
时,您会得到 object
,但它并不特定于对象的 class。
然而,当你查看一个对象时prototype.toString()
它也会return"object",但是当你查看一个对象原型并传入一个对象时,它returns对象和对象的class。
您可以在 ECMAScript5 spec (§15.2.4.2) 中看到关于 Object.prototype.toString 方法的内容:
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
最后一个是"how"的答案。
我正在查看代码以确定一个对象是否是一个数组,我遇到了 this answer。
代码运行良好,但我无法理解它是如何与 [object Array]
我试图获取 typeof Array
,但出现错误。所以我对这段代码感到困惑
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
我很想知道对对象的 toString.call( _ON_AN_ARRAY_ )
方法调用如何正确获取数组对象的类型。
从技术上讲,数组是一个对象,所以当您执行 typeof arrayVar
时,您会得到 object
,但它并不特定于对象的 class。
然而,当你查看一个对象时prototype.toString()
它也会return"object",但是当你查看一个对象原型并传入一个对象时,它returns对象和对象的class。
您可以在 ECMAScript5 spec (§15.2.4.2) 中看到关于 Object.prototype.toString 方法的内容:
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
最后一个是"how"的答案。