开发者问题收集

随机数不正确 - Javascript

2018-02-04
83

我试图从数组中获取随机用户名和密码,并检查当前用户名密码是否与之前的用户名密码相同。如果相同,我想获取不同的用户 ID,并从数组中传递。我写了下面的代码,但它也选择了相同的用户名密码。

let usernames = ["uname1", "uname2"],
        passwords = ["pass1", "pass1"];

    let rand, prevRand;
    prevRand = _.random(0, usernames.length - 1);
    rand = _.random(0, usernames.length - 1);

    console.log("rand " + rand)
    console.log("prevrand " + prevRand)


    if (rand !== prevRand) {
        console.log("uname!==: " + usernames[rand])
        console.log("pass!==: " + passwords[rand])
        prevRand = rand;
    } else {
        while (rand !== prevRand) {
            rand = _.random(0, usernames.length - 1);
            console.log("newrand " + rand)

        }
        prevRand = rand;
        console.log("unamenew " + usernames[rand])
        console.log("passnew " + passwords[rand])

    }

请纠正我的逻辑。谢谢。

2个回答

您的 while (rand !== prevRand) 循环永远不会执行,因为它位于 else 语句内,这意味着 rand == prevRand 。尝试将 while 循环更改为 do..while

查看示例(我已将 _.random 替换为 Math.random 以在没有外部库的情况下运行)

let usernames = ["uname1", "uname2", "uname3", "uname4"],
    passwords = ["passw1", "passw2", "passw3", "passw4"];

let rand, prevRand;
prevRand = Math.floor(Math.random() * (usernames.length));
rand = Math.floor(Math.random() * (usernames.length));

console.log("rand " + rand)
console.log("prevrand " + prevRand)


if (rand !== prevRand) {
    console.log("uname " + usernames[rand])
    console.log("pass " + passwords[rand])
    prevRand = rand;
} else {
    do {
        rand = Math.floor(Math.random() * (usernames.length));
        console.log("newrand " + rand)
    } while (rand == prevRand);
    prevRand = rand;
    console.log("unamenew " + usernames[rand])
    console.log("passnew " + passwords[rand])
}
Kirill Simonov
2018-02-04

else 情况下,rand === prevRand 为真,因此它永远不会进入 while 循环。

相反,循环必须在 rand 等于 prevRand 时循环。

  while (rand === prevRand) {
        rand = _.random(0, usernames.length - 1);
        console.log("newrand " + rand)
 }

每次它们相等时,都应为 rand 赋予一个新值,因此它们可以不同。

Hristo93
2018-02-04