簡體   English   中英

我可以在console.log中將對象打印為類似於日期的字符串嗎?

[英]Can I print Object as string like Date in console.log?

當我創建新的Date對象並使用console.log時,對象不是時間而是字符串。 但是,MyObject打印為對象。

例:

const date = new Date();
console.log(date);

const MyObject = function() {
  this.name = 'Stackoverflow',
  this.desc = 'is Good'
};
console.log(new MyObject());

結果:

2017-04-06T06:28:03.393Z
MyObject { name: 'Stackoverflow', desc: 'is Good' }

但是我想不使用函數或方法來打印如下格式的MyObject。

Stackoverflow is Good

在java中,我可以重寫toString ()來實現這一點。 JavaScript也可能嗎?

我不認為console.log提供任何機制來告訴它要使用哪種表示形式的對象。

你可以做console.log(String(new MyObject())); 並給MyObject.prototype一個toString方法:

const MyObject = function() {
  this.name = 'Stackoverflow';
  this.desc = 'is Good';
};
MyObject.prototype.toString = function() {
    return this.name + this.desc;
};

當您使用ES2015 +功能(我從const看到)時,您可能還會考慮class語法:

class MyObject {
  constructor() {
    this.name = 'Stackoverflow';
    this.desc = 'is Good';
  }
  toString() {
    return this.name + this.desc;
  }
}

提示:在javascript中,您仍然可以使用“替代”方法來實現它

演示:

let myobj={id:1,name:'hello'};

Object.prototype.toString=function(){ 

   return this.id+' and '+this.name

}; //override toString of 'Global' Object.

console.log(obj.toString());// print: 1 is hello

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM