js中的toString

返回对象的字符串表示

objectname.toString([radix])参数
objectname 必选项。要得到字符串表示的对象。
radix 可选项。指定将数字值转换为字符串时的进制

说明
toString 方法是所有内建的 JScript 对象的成员。它的操作依赖于对象的类型: 对象 操作
Array 将 Array 的元素转换为字符串。结果字符串由逗号分隔,且连接起来。
Boolean 如果 Boolean 值是 true,则返回 “true”。否则,返回 “false”。
Date 返回日期的文字表示法。
Error 返回一个包含相关错误信息的字符串。
Function 返回如下格式的字符串,其中 functionname 是被调用 toString 方法函数的名称:
function functionname( ) { [native code] }
Number 返回数字的文字表示。
String 返回 String 对象的值。
默认 返回 “[object objectname]”,其中 objectname 是对象类型的名称。

使用toString方法判断对象类型

function getType(o) {

    var _t;

    return ((_t = typeof (o)) == "object" ? o == null && "null"

            || Object.prototype.toString.call(o).slice(8, -1) : _t)

            .toLowerCase();

}

执行结果:


getType("abc"); //string
getType(true); //boolean
getType(123); //number
getType([]); //array
getType({}); //object
getType(function(){}); //function
getType(new Date); //date
getType(new RegExp); //regexp
getType(Math); //math
getType(null); //null

From:http://www.2cto.com/kf/201402/279090.html

原文地址:https://www.cnblogs.com/autismtune/p/5281121.html