简体   繁体   English

将 javascript 中的 object 打印到 html dom

[英]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.我正在尝试以各种不同的方式将 object 打印到 HTML DOM 中,因此我可以理解它如何更好地工作。

But the result looks like that:但结果看起来像这样:

Store and retrieve data from local storage.从本地存储中存储和检索数据。 John undefinedJohn 31 New York约翰 undefinedJohn 31 New York

As you can see, it returns "undefinedJohn", and I have no clue why.如您所见,它返回“undefinedJohn”,我不知道为什么。 Can someone explain to me?有人可以向我解释吗? Suggestions for other ways to display objects, arrays and JSON in HTML would also be appreciated. HTML 中显示对象的其他方式的建议,arrays 和 JSON 也将不胜感激。

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 ='' :发生这种情况是因为您声明了temp变量但没有对其进行初始化,因此它将 undefined 作为一个值,只需遵循以下工作代码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 .它说undefinedJohn因为您没有声明变量temp So, the default value is undefined .因此,默认值为undefined When you add a different string on to undefined , like 'John' , it will become 'undefinedJohn' .当您在undefined上添加不同的字符串时,例如'John' ,它将变为'undefinedJohn'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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