console.log传入对象时参数形式不同为何返回结果有差异?
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
objdirectly. 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

