界别复杂数据类型Object.prototype.toString.call()
区分复杂数据类型Object.prototype.toString.call()
在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
所以:要想区别对象、数组、函数单纯使用 typeof 是不行的。
ECMA 5.1 中关于该方法的描述是这样的:
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 "]“.
方法结果如下:
在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
所以:要想区别对象、数组、函数单纯使用 typeof 是不行的。
[b] Object.prototype.toString.call() [/b]
ECMA 5.1 中关于该方法的描述是这样的:
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 "]“.
方法结果如下:
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]