[英]Javascript objects in array of objects,are different using console.log
[英]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.