toString()方法
1、返回一个数字对应的字符串
2、返回一个表示该对象的字符串
3、检测对象类型
Object.prototype.toString()方法
返回对象的类型字符串,可用来判断一个值的类型
不能直接用toString()以防被对象重写
用call方法
const num = 123;
console.log('第一:',num.toString());
//第一: 123
class Student {
constructor(name,age){
this.name = name;
this.age = age;
}
}
const p = new Student('tom', 11);
console.log('第二:', p.toString())
//第二: [object Object]
class Person {
constructor(name, age){
this.name = name;
this.age = age;
}
toString(){
return '我的名字' + this.name
}
}
const q = new Person('少林', 18);
console.log('第三:重写后:',q.toString());
//第三:重写后: 我的名字少林
/**
* 想通过toString()方法查看对象的类型
*/
console.log('第三:原型:',Object.prototype.toString.call(q));
//第三:原型: [object Object]
/** call()方法也可以带参数
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");
*/
const mm = '123';
console.log('第四:',Object.prototype.toString.call(mm));
// -> 第四: [object String]
console.log('第五:随机数:',Math.random().toString());
//第五:随机数: 0.6868595385590079
console.log('第五:二进制:',Math.random().toString(2));
//第五:二进制: 0.0001111000110011101111100001111101011010011110111111
console.log('第五:36进制:',Math.random().toString(36));
//第五:36进制: 0.8c67vno1ll3
console.log('第五:随机字符:',Math.random().toString(36).substr(2).length);
//第五:随机字符: 11
console.log('第五:参数为0:',Math.random().toString(0));
//直接报错