+ 1

Unable to display Javascript object in Solo Learn output window

Hello guys, the tutorial which I have been following always uses console.log() to display the object. I am trying to practise javascript on Solo Learn, but I am unable to display the object In the Output window. My code is as follows: var car = { model: "Tesla", color: "silver" }; document.write(car); The output becomes this: [object Object] Beginner here, please help, thank you! Regards Ben

12th Jul 2019, 12:51 AM
Ben
2 Respostas
+ 4
Here car is an object, we need it's string representation to be written in document To convert JavaScript object to it's string representation (JSON), we can use JSON.stringify(obj) method var car = { model: "Tesla", color: "silver" }; document.write(JSON.stringify(car)); Or if you want the output in proper formatting as Gordon suggested, do this var car = { model: "Tesla", color: "silver" }; var s = JSON.stringify(car, null, 4); // makes string json in proper formatting but with newline charecters and spaces s = s.replace(/\n/g, "<br/>"); // replace all \n with <br> using global matching s = s.replace(/ /g, "&nbsp;") // replace all spaces with &nbsp; document.write(s);
12th Jul 2019, 1:08 AM
Om Kumar
Om Kumar - avatar
+ 1
nice answer and if with formatting add null, 4
12th Jul 2019, 1:22 AM
Gordon
Gordon - avatar