简体   繁体   English

如何从 JavaScript 中的多个不同 arrays 中获取随机字符

[英]How to get random characters from multiple different arrays in JavaScript

const array1 = ["A", "b", "C", "D", "f"]
const array2 = ["❤️", "🔥", "👋", "🦑", "😅"]
const array3 = ["0", "1", "2", "3", "4", "5"]


function renderItem() {
    let randomI = Math.floor(Math.random() * array1.length)
    console.log(array2[randomI])
}


function generateRandom () {
    let randomValue = ""
    for(let i = 0; i < 4; i++) {
        randomValue += renderItem()
    }
    return randomValue
}

I create an input field in HTML where the user can select a number between (6 - 18).我在 HTML 中创建了一个输入字段,用户可以在其中 select (6 - 18)之间的数字。 and two input checkboxes.和两个输入复选框。 if both or one of them are checked✅ I want to generate random characters from three(3) of the arrays or from two(2) different arrays.如果两个或一个都被选中✅我想从 arrays 的三 (3) 个或从两个 (2) 不同的 arrays 生成随机字符。 if none of theme are not checked I want to generate random characters from the first array.如果没有检查任何主题,我想从第一个数组中生成随机字符。

now my question is how do I get random eg(10) characters from those 3 different arrays?现在我的问题是如何从这 3 个不同的 arrays 中获取随机的 eg(10) 个字符?

maybe do a 2d array?也许做一个二维数组? if you don't want to change the original arrays.如果您不想更改原来的 arrays。

const arr = [array1, array2, array3]
function renderItem() {
    //randomly select an array
    let randArrIndex= Math.floor(Math.random() * arr.length)
    //now select a random Item from that array (we need it's length to get a valid index)
    let randItemIndex = Math.floor(Math.random() * arr[randArrIndex].length)
    console.log(arr[randArrIndex][randItemIndex])
}

sorry if I didn't understand the question correctly抱歉,如果我没有正确理解这个问题

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

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