toString方法大总结

536 阅读3分钟

每天做个总结吧,坚持就是胜利!

    /**
        @date 2021-05-29
        @description toString()方法大总结
    */

壹(序)

今天在文章: 【JS 进阶】你真的掌握变量和类型了吗中发现toString的一个用法:

const num = 10;

console.log(num.toString(2)); // '1010'

发现对toString方法的理解还不够,所以总结一下。

贰(详解)

String: 返回String对象的字符串形式;

const str = new String('test');

console.log(str.toString()); // 'test'

Number: 返回Number对象的字符串形式;可指定参数radix(数字到字符串的转换基数(2-36),默认为10,超出范围抛出则RangeError;如果Number是负数,会保留符号

// 变量形式
const num = 12;

console.log(num.toString(2)); // '1100'

// 数字形式需要用()包裹起来
console.log(12.toString(2)); // Uncaught SyntaxError: Invalid or unexpected token
console.log((12).toString(2)); // '1100'

// 负数情况,-0返回'0'
console.log((-1).toString()); // '-1'

console.log((-0).toString()); // '0'

Boolean:返回Boolean对象的字符串形式;当与字符串连接时,自动调用toString方法;

console.log(false.toString()); // 'false'
console.log('this is ' + true); // 'this is true'

Symbol:返回symbol 对象的字符串形式;无法与字符串直接连接;

console.log(Symbol('a') + 'b'); // Uncaught TypeError: Cannot convert a Symbol value to a string

Symbol('a').toString(); // 'Symbol(a)'

BigInt: 与Number相似,但是不会处理后面的n;且可以直接以原始形式调用toString方法,大部分情况不需要()

// 变量形式
const bigintNum = 12;

console.log(bigintNum.toString(2)); // '1100'

// 数字形式,-0n需要用()包裹
console.log(12n.toString(2)); // '1100'
// -0n.toString()其实是- + 0n.toString();
console.log(typeof -0n.toString()); // 'number'

// 负数情况
console.log(-12n.toString(2)); // '-1100'
console.log((-0n).toString()); // '0'

Object: 所有对象都返回[object Object],调用Object.prototype.toString.call(obj)返回 [object type],其中 type 是对象的类型;所以可以用Object的toString方法检测数据类型;

const obj = {a: 1};
console.log(obj.toString()); // [object Object]

console.log(Object.prototype.toString.call(obj)); // [object Object]
console.log(Object.prototype.toString.call('test')); // [object String]
console.log(Object.prototype.toString.call(1)); // [object Number]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(1n)); // [object BigInt]
const foo = function() {
    return 'foo';
}
console.log(Object.prototype.toString.call(foo)); // [object Function]
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call(new Date())); // [object Date]
console.log(Object.prototype.toString.call(/test/)); // [object RegExp]

Array: 返回当前数组的所有元素的字符串形式,用,隔开;其中null和undefined会转换为''

console.log(['test', 1, true, null, undefined, {a: 1}, function() {}, new Date()].toString());
// test,1,true,,,[object Object],function() {},Sun May 30 2021 20:06:22 GMT+0800 (中国标准时间)

Function: 返回一个表示当前函数源代码的字符串;Function.prototype.toString()传入任何参数都是返回function () { [native code] }

function sum(a, b) {
  return a + b;
}

console.log(sum.toString()); // 'function sum(a, b) {
                                   return a + b;
                                 }'
console.log(Function.prototype.toString(1)); // 'function () { [native code] }'

Date: 返回一个美式英语日期格式的字符串,与字符串连接会自动调用toString方法;

console.log(new Date().toString()); // Sun May 30 2021 19:30:26 GMT+0800 (中国标准时间)
console.log('current time: ' + new Date().toString()); // current time: Sun May 30 2021 19:31:04 GMT+0800 (中国标准时间)

叁(注意点)

  1. Number类型直接调用时,需要使用()包裹,否则报错;
  2. BigInt类型除了-0n需要使用()包裹,其他不需要,不包裹的-0n.toString()其实是- + 0n.toString()
  3. 除了Symbol,其他类型在与字符串连接时,都是自动调用toString方法;
  4. 除了Object,调用其他类型原型上的toString方法时,只能处理同样的类型,比如:
Number.prototype.toString.call('test'); // Uncaught TypeError: Number.prototype.toString requires that 'this' be a Number
  1. 使用Object.prototype.toString.call可以检测所有数据类型;

肆(引申)

实现所有数据类型检查函数:

function typeCheck(val) {
    return Object.prototype.toString.call(val).slice(8, -1);
}

console.log(typeCheck(1)); // "Number"
console.log(typeCheck(true)); // "Boolean"