简体   繁体   English

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

[英]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.我正在编写一个程序来使用 JavaScript 猜测输入,为此我必须从数组中选择一个随机元素。 However, after trying to debug it with Chrome DevTools, I found out that it's returning the whole array instead of just the element.但是,在尝试使用 Chrome DevTools 对其进行调试后,我发现它返回的是整个数组,而不仅仅是元素。 EDIT: I also made sure it had nothing to do with the method used to select a random element.编辑:我还确保它与用于 select 随机元素的方法无关。 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!提前致谢!

alphabet.slice returns an array. alphabet.slice返回一个数组。

When you charset.push(alphabet.slice(.......)) you are pushing an array, so at the end charset is an array of arrays.当您charset.push(alphabet.slice(.......))时,您正在推送一个数组,因此最后的charset是一个 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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM