如何在Node.js Telegram Bot中正确显示对象,避免[object object]
Node.js Telegram Bot 正确展示对象内容的解决方法
当你直接在模板字符串中插入对象 _coinList 时,JavaScript 会默认调用对象的 toString() 方法,返回 [object Object],这就是你看到该内容的原因。以下是几种正确展示对象内容的方式:
方式一:将对象转为 JSON 字符串
使用JSON.stringify()把对象转为可读的字符串格式,添加缩进还能让结构更清晰:await bot.sendMessage(chat_id, `The current price of ${JSON.stringify(_coinList, null, 2)}.`);注意:如果对象包含循环引用,这个方法会报错,需要提前处理。
方式二:提取对象的特定属性
如果你只需要对象中的部分信息,直接提取对应字段即可,比如假设_coinList包含name和price属性:await bot.sendMessage(chat_id, `The current price of ${_coinList.name} is ${_coinList.price}.`);方式三:自定义对象的 toString 方法
给对象的类添加自定义的toString()方法,让它返回你需要的格式:// 假设 _coinList 是 Coin 类的实例 class Coin { constructor(name, price) { this.name = name; this.price = price; } toString() { return `${this.name}: ${this.price}`; } } // 发送消息时直接使用对象 await bot.sendMessage(chat_id, `The current price of ${_coinList}.`);
内容的提问来源于stack exchange,提问作者Pau
相关产品推荐
相关产品推荐

