Skip to content
Advertisement

Picking random element from array in JavaScript returns the whole array

I’m writing a program to guess input using JavaScript, and to do it I have to pick a random element from an array. However, after trying to debug it with Chrome DevTools, I found out that it’s returning the whole array instead of just the element. EDIT: I also made sure it had nothing to do with the method used to select a random element. Here’s some code:

        var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9","~","`","!","@","#","$","%","^","&","*","(",")","-","_","=","+","[","]","{","}","\","|",";",":","'",""",",","<",".",">","/","?"," "]
        var charset = [];
        if(document.getElementById("lowercase").checked){
            charset.push(alphabet.slice(0, 26));
        }
        if(document.getElementById("uppercase").checked){
            charset.push(alphabet.slice(26, 52));
        }
        if(document.getElementById("numbers").checked){
            charset.push(alphabet.slice(52, 62));
        }
        if(document.getElementById("special").checked){
            charset.push(alphabet.slice(62, alphabet.length));
        }
        var word = document.getElementById("input").value;
        var foundword = "";
        while(true) {
            for(i = 0; i < word.length; i++) {
                foundword += charset[Math.floor(Math.random() * charset.length)];
            }
            if(word == foundword) {
                alert("done");
                break;
            }
            foundword = "";
        }

Could anyone help? Thanks in advance!

Advertisement

Answer

alphabet.slice returns an array.

When you charset.push(alphabet.slice(.......)) you are pushing an array, so at the end charset is an array of arrays.

You can use the spread operator – ... – to have the pushed array converted to a series of values:

charset.push(...alphabet.slice(26, 52));

Just to help you get used to the syntax, here are a couple more examples:

let arr = alphabet.slice(26, 52);
charset.push(...arr);

charset.push(...['a', 'b', 'c']);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement