javascript - 输出给了我 [object Object]

标签 javascript node.js

我正在寻找我的问题的答案 - 我的输出是错误的,我不知道到底什么是错误的。也许代码的某些部分丢失了,我真的不知道 - 我还在学习。

我使用node.js(v10.15.3),我只想将console.log输出显示到txt文件。

导出到 txt 文件的输出应如下所示:

[ Card { suit: 'Clubs', value: 3 },   
  Card { suit: 'Clubs', value: 8 },
  Card { suit: 'Diamonds', value: 9 },
  Card { suit: 'Hearts', value: 5 },
  Card { suit: 'Clubs', value: 10 } ]

但在收到的文本文件中我得到

[object Object],[object Object],[object Object],[object Object],[object Object]

下面是我的代码:

console.log = function(msg) {
    fs.appendFile("OutputTask2and3.txt", msg, function(err) {
        if(err) {
          throw err;
        }
    });
}

class Card {
  constructor(suit, value) {
    this.suit = suit;
    this.value = value;
  }
}

class Deck {
  constructor() {
    this.deck = [];
  }

  createDeck(suits, values) {
    for (let suit of suits) {
      for (let value of values) {
        this.deck.push(new Card(suit, value));
      }
    }
    return this.deck;
  }

  shuffle() {
    let counter = this.deck.length,
      temp,
      i;

    while (counter) {
      i = Math.floor(Math.random() * counter--);
      temp = this.deck[counter];
      this.deck[counter] = this.deck[i];
      this.deck[i] = temp;
    }
    return this.deck;
  }

  deal() {
    let hand = [];
    while (hand.length < 5) {
      hand.push(this.deck.pop());
    }
    return hand;
  }
}

let suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
let values = ["Ace", "Jack", "Queen", "King", 2, 3, 4, 5, 6, 7, 8, 9, 10];
let deck = new Deck();


deck.createDeck(suits, values);
deck.shuffle();

console.log(deck.deal())

最佳答案

使用 JSON.parse()

 console.log(JSON.parse(deck.deal()));

关于javascript - 输出给了我 [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193212/

相关文章:

javascript - 如何在 Javascript 中执行线程

node.js - Mongoose 不创建索引

node.js - 输出 css 文件而不是内联

javascript - 将 jQuery 的 UI 小部件与我的 topNav 混合会破坏水平对齐

javascript - node_modules\ng2-dragula\index.js 未导出“DragulaModule”

javascript - 关键帧动画不向后运行

javascript - Requirejs + Backbone.js : TypeError: Can't pass in the router - Router is not a function?

php - 需要在 href 标签中显示 id 但不导航到其他页面

node.js - 如何使用mongoose在nodejs中转换日期格式

javascript - Heroku nodejs 服务器出现 EADDRNOTAVAIL 错误