📜  Javascript对象toString()

📅  最后修改于: 2020-09-27 06:57:34             🧑  作者: Mango

JavaScript Object toString()方法将对象作为字符串返回。

toString()方法的语法为:

obj.toString()

在这里, obj是一个对象。


toString()参数

toString()方法没有任何参数。


从toString()返回值
  • 返回表示对象的字符串 。

注意 :每个从Object派生的Object继承toString() ,如果未重写,则返回"[object ]"


示例:使用toString()
// built-in objects
let num = 10;
// number takes in optional radix argument (numeral base)
console.log(num.toString(2)); // "1010" in binary

console.log(new Date().toString()); // Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time)

// overriding default toString(), custom object
function Dog(name, breed, sex) {
  this.name = name;
  this.breed = breed;
  this.sex = sex;
}

dog1 = new Dog("Daniel", "bulldog", "male");
console.log(dog1.toString()); // [object Object]

Dog.prototype.toString = function dogToString() {
  return `${this.name} is a ${this.sex} ${this.breed}.`;
};

console.log(dog1.toString()); // Daniel is a male bulldog.

输出

1010
Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time)
[object Object]
Daniel is a male bulldog.

推荐读物: JavaScript Object valueOf()