简体   繁体   English

如何使我的条件在此 JavaScript 代码段中工作?

[英]How can I make my conditionals working in this JavaScript piece of code?

I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function.我正在编写一些 JavaScript 代码作为我创建密码生成器应用程序的作业的一部分,我决定将我应该向用户询问的所有问题都放在 function 中。 One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:生成密码的标准之一是选择 8 到 128 之间的字符数。我想确保用户输入正确的数字,否则 function 重新启动并且不会让用户看到确认框的 rest直到他输入所需的数字,所以我这样写:

function askQuestions() {
  let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
  console.log(numOfChracaters);
  if (numOfChracaters >= 8 || numOfChracaters <= 128) {
    let hasUppercase = confirm("Do you want your password to include uppercase letters?");
    let hasLowercase = confirm("Do you want your password to include lowercase letters?");
    let hasNumber = confirm("Do you want your password to include numbers?");
    let hasSpecialCharacters = confirm("Do you want your password to include special characters?");

    let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
    return prefrencesArray;
  } else {
    askQuestions();
  }
} 

But for some reason it doesn't work and still allows user to enter whatever number they want.但由于某种原因,它不起作用,仍然允许用户输入他们想要的任何数字。 Any ideas what did I do wrong here?任何想法我在这里做错了什么?

replace conditional替换条件
numOfChracaters >= 8 || numOfChracaters <= 128
to
numOfChracaters >= 8 && numOfChracaters <= 128

You have made a funny mistake.你犯了一个有趣的错误。 Every number is either >= 8 OR <= 128.每个数字要么 >= 8要么<= 128。

What you're looking for is && operator, because both sides need to be true at the same time.您正在寻找的是&&运算符,因为双方都需要同时为真。

You can use an infinite loop to run till the requirements are met您可以使用无限循环运行直到满足要求

let numOfChracaters = 0;
while(numOfChracaters < 8) {
  numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
}

if (numOfChracaters >= 8 && numOfChracaters <= 128)

Since for your OR ( || ) operator, it was true for the condition numOfChracaters <= 128, thus according to you inputs (false || true)=> returns true. and (false && true)=> return false因为对于您的 OR ( || ) 运算符,条件 numOfChracaters <= 128 为 true,因此根据您的输入(false || true)=> returns true. and (false && true)=> return false (false || true)=> returns true. and (false && true)=> return false

Explaining your mistake so that next time you don't make such error.解释你的错误,以便下次你不会犯这样的错误。

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

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