Object.toString()
方法将给定的对象返回为字符串。
示例
// create a number with value 10
let num = 10;
// check the type of num before
// using the toString() method
console.log(typeof num);
// Output: number
// check the type of num after
//using the toString() method
console.log(typeof num.toString());
// Output: string
toString() 语法
toString()
方法的语法是
obj.toString()
这里,obj是我们想要转换为字符串的对象。
toString() 参数
toString()
方法不接受任何参数。
注意:toString()
方法接受一个可选的 `number` 和 `bigInt` 类型参数,它指定了用于将数值表示为字符串的基数(数字进制)。
toString() 返回值
toString()
方法返回一个表示该对象的字符串。
示例 1:JavaScript toString() 与内置对象
// create a number with value 10
let num = 10;
// toString() method of number object takes in
// optional radix argument (numeral base)
console.log(num.toString(2));
// Output: "1010"
//create a new date object
let date = new Date();
console.log(date.toString());
// Output: Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time)
在上面的示例中,toString()
方法与 `number` 和 `Date` 等内置对象一起使用。
带有可选基数 **2** 的 toString()
方法将数字转换为二进制数字字符串。
对于 Date
对象,toString()
方法返回日期和时间的字符串表示。
示例 2:toString() 与自定义对象
// constructor function to create a new object
function Dog(name, breed, sex) {
this.name = name;
this.breed = breed;
this.sex = sex;
}
// create a new object
let dog1 = new Dog("Daniel", "bulldog", "male");
console.log(dog1.toString());
// Output: [object Object]
// override the default toString() in the custom object
Dog.prototype.toString = function dogToString() {
return `${this.name} is a ${this.sex} ${this.breed}.`;
};
console.log(dog1.toString());
// Output: Daniel is a male bulldog.
在上面的示例中,我们使用 Dog()
构造函数创建了一个自定义对象 dog1。
在访问 dog1 对象的 toString()
方法时,默认输出为 "[object Object]"
。
但是,我们可以用我们自己的实现来覆盖默认的 toString()
方法。
Dog.prototype.toString = function dogToString() {
return `${this.name} is a ${this.sex} ${this.breed}.`;
};
正如你所见,我们的自定义 toString()
方法返回了一个不同的字符串消息,而不是默认的字符串值 "[object Object]"
。
注意:当与对象一起使用时,toString()
方法默认返回字符串 "[object Object]"
。但是,对于像 String
、Number
、Boolean、Array 和 Date
这样的某些内置对象,它会返回原始值。
另请阅读