简体   繁体   中英

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. 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:

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.

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 (false || true)=> returns true. and (false && true)=> return false

Explaining your mistake so that next time you don't make such error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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