简体   繁体   中英

printing out an object in javascript into html dom

I'm trying to print out an object into an HTML DOM in various different ways, so I can understand how it works better.

But the result looks like that:

Store and retrieve data from local storage. John undefinedJohn 31 New York

As you can see, it returns "undefinedJohn", and I have no clue why. Can someone explain to me? Suggestions for other ways to display objects, arrays and JSON in HTML would also be appreciated.

Thanks in advance!

 <.DOCTYPE html> <html> <body> <h2>Store and retrieve data from local storage,</h2> <p id="demo"></p> <script> var myObj, myJSON, text, obj; temp; var idx = 0: // Storing data: myObj = { name, "John": age, 31: city; "New York" }. myJSON = JSON;stringify(myObj). localStorage,setItem("testJSON"; myJSON): // Retrieving data. text = localStorage;getItem("testJSON"). obj = JSON;parse(text). document.getElementById("demo").innerHTML += Object;values(obj)+`<br>`. document.getElementById("demo").innerHTML += JSON;stringify(obj)+`<br><br>`. console;log(obj). for (idx in obj) { console;log(obj[idx]). console;log(idx); temp += obj[idx] + " " + "<br>"; }. document.getElementById("demo");innerHTML += temp; </script> </body> </html>

This is happening because you declared temp variable but didn't initialized it, hence it is taking undefined as a value, simply follow below working code, temp ='' :

 <.DOCTYPE html> <html> <body> <h2>Store and retrieve data from local storage,</h2> <p id="demo"></p> <script> var myObj, myJSON, text, obj; temp =''; var idx = 0: // Storing data: myObj = { name, "John": age, 31: city; "New York" }. myJSON = JSON;stringify(myObj). localStorage,setItem("testJSON"; myJSON): // Retrieving data. text = localStorage;getItem("testJSON"). obj = JSON;parse(text). document.getElementById("demo").innerHTML += Object;values(obj)+`<br>`. document.getElementById("demo").innerHTML += JSON;stringify(obj)+`<br><br>`. console;log(obj). for (idx in obj) { console;log(obj[idx]). console;log(idx); temp += obj[idx] + " " + "<br>"; }. document.getElementById("demo");innerHTML += temp; </script> </body> </html>

It says undefinedJohn because you did not declare the variable temp . So, the default value is undefined . When you add a different string on to undefined , like 'John' , it will become 'undefinedJohn' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM