简体   繁体   中英

Why am i only getting the last element of an array as output?

I tried making a login system with a button that shows which users are online in javascript. I type in a name and click login. After that i can choose to show the list of online users or type in another name. What i want is that when i click Show List, a list of the online users (all the names i logged in) shows up. The problem is that i am only getting the last name i logged in with in the list. All the other names do not show up.

If you run the snippet below and try to login multiple names, you will only get the last name that you logged in with:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>javascript</title> <link href="" rel="stylesheet"> <script type="text/javascript"> var playerlist; function login(){ var player = document.getElementById('loginField').value; var players = new Array(); players.push(player); playerlist = players.join("<br>"); } </script> </head> <body> <input type="text" id="loginField" placeholder="Username:"> <input type="button" value="Login" onclick="login()"> <input type="button" value="Show List" onclick="showlist()"><br> <script type="text/javascript"> function showlist(){ document.write(playerlist); } </script> </body> </html> 

What am i doing wrong here?

Thank you in advance.

Because you are creating a new array every time you call the login method. So you lose the previous array where you pushed some string earlier.

Move the array declaration outside of your method so that it stays between multiple calls to your login method.

var players = []; 
function login()
{
   var player = document.getElementById('loginField').value;
   players.push(player);
   playerlist = players.join("<br>");
}

I also changed the new Array() to [] . Both are same, but crockford( creator of json ) suggests to use [] . Thanks @Rayon Dabre for suggesting that.

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