ITeye博客

区分复杂数据类型Object.prototype.toString.call()

小丑鱼0703 · 2015-02-09 14:16 · JavaScript · Web前端 · Markdown

在 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 ““. If the this value is null, return ““. Let O be the result of calling ToObject passing the this value as the argument. Let class be the value of the ] internal property of O. Return the String value that is the result of concatenating the three Strings ““.

ECMAScript 5 中,为了方便,对 null 和 undefined 调用 Object.prototype.toString 方法, 其返回值由 Object 变成了 Null 和 Undefined。方法结果如下:


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(null);//[object null]
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]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。