关于Javascript的toString方法,你所需要知道的

1,626 阅读3分钟

昨天在看一道关于判断变量类型的面试题时,提到了运用Object.prototype.toString.call(arg)来判断变量类型。我由此对toString这个常常出现但并不被人重视的方法产生了兴趣,于是乎,尝试写下一篇博客,记录一些和它相关的知识点。如有错误,欢迎指正。

首先,我们知道,每个对象实例都可以调用toString方法。对于一切皆对象的JavaScript来说,ES5的五种基本类型(Boolean,String,Number,Null,Undefined)的前三种也可以使用toString转换成字符串(Null和Undefined可以使用String()方法来转换)。

但不是每个对象的toString方法,都是直接继承自Object.prototype.toString的。许多内置对象比如Function,Array,都在自身都层级上对该方法进行了重写,下面让我带大家一起看看,不同对象上的toString方法各有什么特点。

1.Function

如果我们对一个function类型的对象(或者直接称为函数)调用toString,输出的是该函数的源码:

function test(){
    console.log('hello')
}
test.toString() 
/* 对于用户定义的函数,将输出源码
    "function test(){
        console.log('hello')
    }"
*/
    
test.toString.toString()
/*对一个内置函数使用toString,将会输出:
"function toString() { [native code] }"
*/
  • 当一个函数需要表示为一个字符串,或者当函数与一个字符串连接时,toString方法会自动被调用
  • Function.prototype.toString被一个非函数类型调用时,将会抛出一个错误
Function.prototype.toString.call('foo'); // TypeError

2.Array

当对一个数组使用toString时,将会返回数组内每个成员调用toString后的结果,并以逗号分割

let arr = [test,null,[1,2,3]]
arr.toString()
/* 其中test是上文中定义的函数test,由于null没有toString方法,将会返回空字符串
   最终结果为:
    "function test(){
    console.log('hello')
    },,1,2,3"
*/

3.Number

当对一个数字使用toString后,返回的结果毫无疑问是该数字对应的字符串。但值得一提的是,Number类型的toString方法可以传入一个参数,该参数为输出数字字符串的基数。

    var num = 10;
    num.toString() // "10"
    num.toString(2) // "1010"
    num.toString(8) // "12"
    num.toString(16) // "a"

4.Date

对日期对象使用toString后,返回的是一个在ECMA-262标准中被规定好的字符串

    let date = new Date()
    date.toString() // "Wed May 27 2020 23:15:01 GMT+0800 (中国标准时间)"

值得一提的是,Date 类型还有一些专门用于将日期格式化为字符串的方法,这些方法如下。

  • toDateString()——以特定于实现的格式显示星期几、月、日和年;
  • toTimeString()——以特定于实现的格式显示时、分、秒和时区;
  • toLocaleDateString()——以特定于地区的格式显示星期几、月、日和年;
  • toLocaleTimeString()——以特定于实现的格式显示时、分、秒;
  • toUTCString()——以特定于实现的格式完整的 UTC 日期

5.回到Object.prototype.toString

说了这么多,让我们回到所有这些toString的祖先上来。之所以所有对象都能够调用toString方法,正是因为其原型链的源头Object.prototype上存在这个方法。 MDN上对该方法做了如下阐述:

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.

现在我们知道了,之所以能用Object.prototype.toString来判断变量类型,正是因为这个“原始”的方法,返回的是"[Object type]"这种格式的字符串,其中的type就代表着该变量的类型(甚至包括null和undefined)

const toString = Object.prototype.toString;

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]
    

好了,以上就是我对toString的总结,你有什么想法?欢迎留言让我知道😁