简体   繁体   中英

Seeing “undefined” printed when iterating an array

I am iterating a JavaScript array object. I have written a function which iterates the array element. it works but above the result there is written 'undefined'. I don't want to see this, it would be great help to know how to solve this undefine word thing.

 var userlist = [{ "username": "Tom", "Current_latitude": 23.752805, "Current_longitude": 90.375433, "radius": 500 }, { "username": "Jane", "Current_latitude": 23.752805, "Current_longitude": 90.375433, "radius": 400 }, { "username": "Dave", "Current_latitude": 23.765138, "Current_longitude": 90.362601, "radius": 450 }, { "username": "Sarah", "Current_latitude": 23.792452, "Current_longitude": 90.416696, "radius": 600 }, { "username": "John", "Current_latitude": 23.863064, "Current_longitude": 90.400126, "radius": 640 } ]; var x = Tom(userlist); function Tom(user) { var text; for (var i = 0; i < user.length; i++) { text += "<li>" + user[i].username + "</li>"; }; //text+="</ul>" document.getElementById("demo").innerHTML = text; } //document.getElementById("demo").innerHTML=userlist[0].username+" "+userlist[0].Current_latitude + " " + userlist[0].Current_latitude+"" + userlist[0].Current_longitude+" "+ userlist[0].radius; 
 <p>How to create A javaScript Object Array.</p> <p id="demo"></p> 

You need to initialize your valiable text to an empty string, like this:

var text = "";

Uninitialized variables in JavaScript default to the special value undefined , which is found as text in the concatenation.

As noted in the comments, there's an in issue in your HTML too: <li> tags should only appear inside a containing <ul> , <ol> or <menu> tag. You may consider changing your <li> ... </li> to something like <div> ... </div> or wrapping the text concatendated text with <ul> ... </ul> .

It's because you haven't initialised your variable:

var text;  //text is undefined at this point
for (var i = 0; i < user.length; i++) 
{
    //the first iteration of the loop will append to "undefined"
    text+="<li>"+ user[i].username+"</li>";
};

Simply give it an initial value:

var text = '';
for (var i = 0; i < user.length; i++) 
{
    text+="<li>"+ user[i].username+"</li>";
};

As noted by Juhana, however, this isn't generating valid markup. You can uncomment your closing tag, and initialise text to <ul> instead:

var text = '<ul>';
for (var i = 0; i < user.length; i++) 
{
    text+="<li>"+ user[i].username+"</li>";
};
text += "</ul>";

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