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

console.log传入对象时参数形式不同为何返回结果有差异?

Why console.log Shows [object Object] When Concatenating Objects with Strings

Great question! This boils down to two core JavaScript behaviors: how console.log handles multiple arguments, and how the language converts objects to strings during concatenation. Let’s break this down clearly:

1. Passing the object as a separate argument

const obj = {animal: "Dog"};
console.log("obj:", obj); // Output: { animal: 'Dog' }

Here, console.log is built to process distinct, separate arguments individually. It doesn’t try to mash them into a single string first:

  • It logs the string "obj:" as-is
  • Then, it inspects the obj directly. Browsers and Node.js’s console tools are designed to display structured object data for debugging—this is a deliberate feature to let you see the object’s key-value pairs at a glance.

2. Concatenating the object into a string

console.log("obj: " + obj); // Output: obj: [object Object]
console.log(`obj: ${obj}`); // Output: obj: [object Object]

Both the + operator and template literals (${}) trigger string coercion. JavaScript automatically converts any non-string value to a string before combining it with other text.

By default, all plain JavaScript objects inherit the toString() method from Object.prototype, which returns the generic string "[object Object]". This is the default behavior for any object that doesn’t have a custom toString() method defined.

Quick fix to display object content in a string

If you want to include the object’s actual data in a string, use JSON.stringify() to convert it to a human-readable JSON string:

console.log(`obj: ${JSON.stringify(obj)}`); // Output: obj: {"animal":"Dog"}

Note: JSON.stringify() has limitations—it won’t serialize functions, circular references, or some non-JSON data types—but it works perfectly for plain objects like your example.

内容的提问来源于stack exchange,提问作者Jamie Sauve

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:24:36