分享
三行代码  ›  专栏  ›  技术社区  ›  ACW

在JavaScript中从数组中选择随机元素返回整个数组

  •  0
  • ACW  · 技术社区  · 1 周前

            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 = "";
            }
    

    有人能帮忙吗? 提前谢谢!

    1 回复  |  直到 1 周前
        1
  •  2
  •   obe    1 周前

    alphabet.slice 返回一个数组。

    当你 charset.push(alphabet.slice(.......)) charset

    ...

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

    为了帮助您习惯语法,下面是几个示例:

    let arr = alphabet.slice(26, 52);
    charset.push(...arr);
    
    charset.push(...['a', 'b', 'c']);