tostring

1.Number

toString() 方法返回指定 Number 对象的字符串表示形式。

 var count=10;
 console.log(count.toString())//10
 console.log(count.toString(2))//1010

2.Array

toString() 返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', '1a'];
 console.log(array1.toString());//1,2,a,

3.String

toString() 方法返回指定对象的字符串形式

var st1 = new String('hello')
console.log(st1.toString())//hello

4.Function

toString() 方法返回一个表示该对象的字符串。

每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。

function Dog(name) {
            this.name = name;
        }

        const dog1 = new Dog('Gabby');
        console.log(dog1.toString())//[object Object]

 

function Dog(name,sex) {
            this.name = name;
            this.sex=sex
        }
        Dog.prototype.toString = function dogToString() {
            var ret = "Dog " + this.name + " is a " + this.sex 
            return ret;
        }
        const dog1 = new Dog('Gabby','femal');
        console.log(dog1.toString())

5.

可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg

console.log(Object.prototype.toString(new Date))//[object Object]
        console.log(toString.call(new Date)); // [object Date]
        console.log(toString.call(new String)); // [object String]
        console.log(toString.call(Math)); // [object Math]

 

 

 

posted @ 2020-08-10 16:40  minfight  阅读(125)  评论(0)    收藏  举报