我正在尝试从数组中随机使用用户名和密码,并检查当前用户名密码是否与以前的用户名密码相同。如果它是相同的,我想采取不同的用户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])
}
请在这里纠正我的逻辑......谢谢。
答案 0 :(得分:1)
您的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])
}

答案 1 :(得分:0)
rand === prevRand在 else 情况下为true,因此它永远不会进入 while 周期。
相反,循环必须循环,而rand等于prevRand
while (rand === prevRand) {
rand = _.random(0, usernames.length - 1);
console.log("newrand " + rand)
}
每当它们相等时,应给出 rand 的新值,因此它们可以不同。