繁体   English   中英

我想生成直到 3 的随机数,但我不想重复它们。 我怎样才能让它工作?

[英]I want to generate random numbers till 3 but i don't want to repeat them. How can i make it work?

function generator(){
    var random = Math.floor(Math.random() * 3);
    var arrays = [];
    for (var i = 0; i < arrays.length; i++){
        if (arrays.length = 0){
            console.log(random);
            arrays.push(random);
        } else if (random = arrays[i]){
            generator();
        } else {
            console.log(random);
            arrays.push(random);
        }
    }
}

我试图将数字推入数组,然后用 for 循环检查它们,但它没有用。 我基本上想知道为什么这段代码不起作用。 在这里使用 for 循环是错误的吗?

好,我知道了。

    var arrays = [];
function generator(){
    var random = Math.floor(Math.random() * 3);
    if (arrays.length == 3){
        stop();
    } else if (arrays.indexOf(random) == -1){
        console.log(random);
        arrays.push(random);
    } else{
        generator();
    }
}

另一种解决方案

let num, already = new Object;

    let start = 0, end = 3;

    for (let i = 0; i < 3;)
    {
        num = (Math.random() * (end - start) + start) ^ 0;
        if (!(num in already))
        {
            already[num] = num;
            i++;
            document.write(String(num));
            if (i < 3)
                document.write(', ');
        }
    }

暂无
暂无

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

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