1. This website uses cookies to improve service and provide a tailored user experience. By using this site, you agree to this use. See our Cookie Policy.
    Dismiss Notice

[JS] array is not depleting.

Discussion in 'HTML & JavaScript' started by Stewielenor, Feb 16, 2020.

Tags:
  1. Stewielenor

    Stewielenor Jr. VIP Jr. VIP

    Joined:
    Apr 9, 2016
    Messages:
    1,594
    Likes Received:
    1,731
    Gender:
    Male
    Occupation:
    Collecting Shadowbanned Accounts
    Home Page:
    The array should be empty after 3 times calling the function, but is it not. Anyone know what I missed?
    Code:
    function getRandomEmail() {
            var emailname = "test1 test2 test3".split(" ");
            const randomElement = emailname[Math.floor(Math.random() * emailname.length)];
            const index = emailname.indexOf(randomElement);
              if (index > -1){ emailname.splice(index, 1);}
              if (emailname && emailname.length > 0) {
           return `${randomElement}@example.com`;
        }else
            return ("no mail available");
        }
    var email = getRandomEmail()
    
     
  2. hakann

    hakann Jr. VIP Jr. VIP

    Joined:
    Oct 10, 2015
    Messages:
    107
    Likes Received:
    41
    Gender:
    Male
    Home Page:
    Every time you call your function it creates
    that same array with 3 elements and takes
    onne random.

    So after one execution array has 2 elements,
    but when you call it 2nd time it creates/overwites
    that 2 element array with new array of 3 elements.

    So every time you call it it makes 3 element array.

    You shoud create array outside of that function
    you call to make it work as you desire.

    Code:
    var emailname = "test1 test2 test3".split(" ");
    function getRandomEmail() {
            const randomElement = emailname[Math.floor(Math.random() * emailname.length)];
            const index = emailname.indexOf(randomElement);
              if (index > -1){ emailname.splice(index, 1);}
              if (emailname && emailname.length > 0) {
           return `${randomElement}@example.com`;
        }else
            return ("no mail available");
        }
    var email = getRandomEmail()
     
    • Thanks Thanks x 2
  3. Stewielenor

    Stewielenor Jr. VIP Jr. VIP

    Joined:
    Apr 9, 2016
    Messages:
    1,594
    Likes Received:
    1,731
    Gender:
    Male
    Occupation:
    Collecting Shadowbanned Accounts
    Home Page:
    yes that was one solutions that didn't work out. I have it covered now thanks !