You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何使用字符串插值打印对象?

Got it, let's break down why ${star} outputs [object Object] and how to print the full object using string interpolation in JavaScript.

First, the reason you're seeing [object Object] is because when you put an object directly into a template literal, JavaScript automatically converts it to a string using the toString() method. By default, all objects inherit the toString() method from Object.prototype, which just returns [object Object]—not super helpful for seeing the actual data!

Here are a few solid ways to fix this:

1. Use JSON.stringify() (most common solution)

This is the go-to method for converting objects to readable strings. It serializes the object into JSON format, and you can even add indentation to make the output pretty:

const star = { id: 1, name: 'Arcturus', visualMag: -0.05 };
console.log(`${JSON.stringify(star, null, 2)}`);

This will output:

{
  "id": 1,
  "name": "Arcturus",
  "visualMag": -0.05
}

A quick note: JSON.stringify() has limitations—like ignoring functions, Symbol values, and throwing errors for circular references. But for most plain objects (like your star example), it works perfectly.

2. Customize the object's toString() method

If you own the object definition, you can override its toString() method to return exactly the format you want. Then, when you use ${star}, it will call this custom method instead of the default one:

const star = { 
  id: 1, 
  name: 'Arcturus', 
  visualMag: -0.05,
  toString() {
    return `Star { id: ${this.id}, name: '${this.name}', visualMag: ${this.visualMag} }`;
  }
};
console.log(`${star}`); // Output: Star { id: 1, name: 'Arcturus', visualMag: -0.05 }

This is great if you need a specific, human-readable format instead of strict JSON.

3. Manually format key-value pairs (for full control)

If you want total control over how each property is displayed, you can use Object.entries() to loop through the object's keys and values, then build the string yourself:

const star = { id: 1, name: 'Arcturus', visualMag: -0.05 };
const starString = `{ ${Object.entries(star).map(([key, val]) => `${key}: ${JSON.stringify(val)}`).join(', ')} }`;
console.log(starString); // Output: { id: 1, name: "Arcturus", visualMag: -0.05 }

This is handy if you need to tweak how individual properties are stringified (like adding quotes around strings but not numbers).

To recap: JSON.stringify() is the easiest and most reliable option for most cases. Use a custom toString() if you need a specific format, or the manual approach for full control.

内容的提问来源于stack exchange,提问作者Ankit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:17:37