如何在if-else语句中调用函数?

时间:2020-10-20 13:30:16

标签: javascript function if-statement

尝试在底部的if-else内部调用pushChar函数,将运行警报,但不会运行该函数。我在做什么错了?

我觉得这与示波器有关,但是我对此很陌生,所以可能不是。

这是一个密码生成器,它从用户选择的选项创建的数组中提取。我想不确定所有要求是否都在最终密码中,如果不是,请重新运行创建密码的功能。

var generateBtn = document.querySelector("#generate");

// Write password to the #password input
function writePassword() {
    var password = generatePassword();
    var passwordText = document.querySelector("#password");

    passwordText.value = password;

}

// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);

//Generate password
function generatePassword() {

//finding out how many characters the user wants in the password with a set range of 8-128
var pwLength = parseInt(prompt("Enter a number between 8-128"));
  while (pwLength < 7 || pwLength > 129 || isNaN(pwLength) || pwLength === null) {
      alert("That's not a valid number. Please enter a number from 8-128.");
      pwLength = prompt("Enter a number between 8-128");
}

//Defining variables
var confirmLower = confirm("Do you want to include lower case characters?");
var confirmUpper = confirm("Do you want to include upper case characters?");
var confirmNumber = confirm("Do you want to include number characters?");
var confirmSpecial = confirm("Do you want to include special characters?");

//If all answers are false, looping back through to get atleast one true response.
while (confirmLower === false && confirmUpper === false && confirmNumber === false && confirmSpecial === false) {
    alert("You need to select one type of character");
    var confirmLower = confirm("Do you want to include lower case characters?");
    var confirmUpper = confirm("Do you want to include upper case characters?");
    var confirmNumber = confirm("Do you want to include number characters?");
    var confirmSpecial = confirm("Do you want to include special characters?");
}

// Various Character Arrays
var lowerCaseChar = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var upperCaseChar = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var numericChar = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
var specialChar = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "{", "}", "|", "[", "]", ";", "'", ":", "<", ">", "?", "/"];

//Array created based on the answers to prompts by the user
var passwordPool = [];

//Creating new array containing the options(arrays) the user chose to include in the password
function generateChar() {
    if (confirmLower) {
        passwordPool.push(...lowerCaseChar);
    }
    if (confirmUpper) {
        passwordPool.push(...upperCaseChar);
    }
    if (confirmNumber) {
        passwordPool.push(...numericChar);
    }
    if (confirmSpecial) {
        passwordPool.push(...specialChar);
    }
}
    generateChar();
    console.log(passwordPool);

   //Creates final array out of random characters from the pool that was created by the users option inputs.
    function pushChar() {
        var randomPassword = [];
        for (var i = 0; i < pwLength; i++) {
            var item = passwordPool[Math.floor(Math.random() * passwordPool.length)];
            randomPassword.push(item);
    }
    return randomPassword;
}
var password = pushChar();


//validate that all of the conditions were met.

var checkUpper = (upperCaseChar.some(ele => password.includes(ele)))
var checkLower = (lowerCaseChar.some(ele => password.includes(ele)))
var checkNumeric = (numericChar.some(ele => password.includes(ele)))
var checkSpecial = (specialChar.some(ele => password.includes(ele)))

console.log(checkUpper);
console.log(checkLower);
console.log(checkNumeric);
console.log(checkSpecial);


if (checkUpper === confirmUpper &&
    checkLower === confirmLower &&
    checkNumeric === confirmSpecial &&
    checkSpecial === confirmNumber) {
    console.log(password);
} else {
        alert("somethings missing");
        console.log(pushChar()); //why won't this run??
}



//Presents randomly generated password to the user as a string. 
  return password.join("");
}

1 个答案:

答案 0 :(得分:-2)

这似乎对我有用,我的代码编辑器给出的唯一问题是您从未定义generateBtn。我唯一更改的是让let和const的var,因为我的编辑器在抱怨它们。

一个问题是您正在重新定义checkUpper等,但这并不引起您的问题。当我运行您的代码(用lets和const替换vars时,我不知道这是否有所不同),当我遇到“缺少的东西”时,pushChar会运行,但您不会更改密码,并且不会-运行检查。我建议您使用ConfirmLower等进行类似的循环。像这样:

const generateBtn = document.querySelector('#generate');

// Write password to the #password input
function writePassword() {
  const password = generatePassword();
  const passwordText = document.querySelector('#password');

  passwordText.value = password;
}

// Add event listener to generate button
generateBtn.addEventListener('click', writePassword);

// Generate password
function generatePassword() {
  // finding out how many characters the user wants in the password with a set range of 8-128
  let pwLength = parseInt(prompt('Enter a number between 8-128'), 10);
  while (pwLength < 7 || pwLength > 129 || Number.isNaN(pwLength) || pwLength === null) {
    alert("That's not a valid number. Please enter a number from 8-128.");
    pwLength = prompt('Enter a number between 8-128');
  }

  // Defining variables
  let confirmLower = false;
  let confirmUpper = false;
  let confirmNumber = false;
  let confirmSpecial = false;

  // If all answers are false, looping back through to get atleast one true response.
  while (confirmLower === false && confirmUpper === false
    && confirmNumber === false && confirmSpecial === false) {
    alert('You need to select one type of character');
    confirmLower = confirm('Do you want to include lower case characters?');
    confirmUpper = confirm('Do you want to include upper case characters?');
    confirmNumber = confirm('Do you want to include number characters?');
    confirmSpecial = confirm('Do you want to include special characters?');
  }

  // Various Character Arrays
  const lowerCaseChar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  const upperCaseChar = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  const numericChar = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
  const specialChar = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '{', '}', '|', '[', ']', ';', "'", ':', '<', '>', '?', '/'];

  // Array created based on the answers to prompts by the user
  const passwordPool = [];

  // Creating new array containing the options(arrays) the user chose to include in the password
  function generateChar() {
    if (confirmLower) {
      passwordPool.push(...lowerCaseChar);
    }
    if (confirmUpper) {
      passwordPool.push(...upperCaseChar);
    }
    if (confirmNumber) {
      passwordPool.push(...numericChar);
    }
    if (confirmSpecial) {
      passwordPool.push(...specialChar);
    }
  }
  generateChar();
  console.log(passwordPool);

  // Creates final array out of random characters from
  // the pool that was created by the users option inputs.
  function pushChar() {
    const randomPassword = [];
    for (let i = 0; i < pwLength; i += 1) {
      const item = passwordPool[Math.floor(Math.random() * passwordPool.length)];
      randomPassword.push(item);
    }
    return randomPassword;
  }

  // validate that all of the conditions were met.
  function checkPassword(password) {
    const checkUpper = (upperCaseChar.some((ele) => password.includes(ele)));
    const checkLower = (lowerCaseChar.some((ele) => password.includes(ele)));
    const checkNumeric = (numericChar.some((ele) => password.includes(ele)));
    const checkSpecial = (specialChar.some((ele) => password.includes(ele)));

    console.log(checkUpper);
    console.log(checkLower);
    console.log(checkNumeric);
    console.log(checkSpecial);

    return checkUpper === confirmUpper
      && checkLower === confirmLower
      && checkNumeric === confirmSpecial
      && checkSpecial === confirmNumber;
  }

  let password = [];
  while (!checkPassword(password)) {
    password = pushChar();
  }

  // Presents randomly generated password to the user as a string.
  return password.join('');
}