簡體   English   中英

在console.log中打印Javascript對象時的不同行為

[英]Different behavior when printing Javascript Objects in console.log

如果我們對對象進行console.log() ,我們將看到其屬性。 但是,如果console.log包含其他字符串,則僅獲得[object Object]

問題:為什么它不打印出對象的屬性? 我們如何使用console.log來打印出我們的字符串和對象的屬性? 如果有幫助,可以使用Underscore.js和節點包。

> myThing = {'name': 'Doge', 'value': 1000}
Object {name: "Doge", value: 1000}

> console.log(myThing)
Object {name: "Doge", value: 1000}

> console.log('Logging: ' + myThing)
Logging: [object Object]

期望的輸出

Logging: Object {name: "Doge", value: 1000}

-在瀏覽器中

因為當您使用console.log('Logging: ' + myThing)它使用字符串連接,其中將對象myThing轉換為字符串表示形式[object Object]

您可以使用

console.log('Logging: ', myThing)

或使用JSON.stringify() -在現代瀏覽器中(對於舊的瀏覽器,請使用json2之類的庫)

console.log('Logging: ' + JSON.stringify(myThing))

Node.js具有一個名為util的內置模塊,您可以使用util.inspect顯示對象。

var util = require("util");
myThing = {'name': 'Doge', 'value': 1000};
console.log(myThing);
console.log('Logging: ' + myThing);
console.log('Logging: ' + util.inspect(myThing));

產量

{ name: 'Doge', value: 1000 }
Logging: [object Object]
Logging: { name: 'Doge', value: 1000 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM