mercredi 22 avril 2020

Cycle through existing users until one isn't found

I'm just messing about really but ran into a problem. I'm trying to create a username when a user clicks on a div within the page.

I want it to store the usernames in an array. If the username already exists in the array I want it to re-run the function to create a new username until it finds one that doesn't exist then put that into the array.

I just can't seem to workout how to achieve this. Could anyone help please? Thank You

$(document).ready(function() {
  jQuery(function() {
    var usernames = [];

    function createUser() {
      var i = Math.floor((Math.random() * 10) + 1);
      var newUser = "Username" + i;
      return newUser;
    }

    $(".CreateUser").click(function() {
      var newUser = createUser();
      if (jQuery.inArray(newUser, usernames) !== -1) {
        newUser = createUser();
        console.log("User Exists");
      } else {
        usernames.push(newUser);
        $(".Usernames").append("<br>" + newUser);
        console.log(usernames);
        console.log("User Added");
      }
    });
  });
});

Aucun commentaire:

Enregistrer un commentaire