【问题标题】:Creating functions to define password characteristics?创建函数来定义密码特征?
【发布时间】:2020-06-06 04:47:47
【问题描述】:

我正在开发一个随机密码生成器,它使用来自用户的提示根据用户定义的参数创建密码。到目前为止,我的提示正常工作并记录了正确的响应,但我刚刚开始学习 javascript,对下一步该去哪里有点困惑。我不知道如何组合可能的密码字符的变量和用户响应的变量。任何帮助表示赞赏!这是我到目前为止的代码:

var generateBtn = document.querySelector("#generate");
// Variables that could possibly be included, based on the user responses
var caps = ["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 lower = ["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 num = [0,1,2,3,4,5,6,7,8,9]
var spec = ['@', '%', '+', '', '/', "'", '!', '#', '$', '^', '?', ':', ',', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.']
// Write password to the #password input

function generatePassword () {
  //Attributing variables based on user responses
var pwLength; 
 pwLength = prompt ("How many characters in your password? Please choose between 8-24.")
  if ((pwLength < 24) && (pwLength > 8)) {
    console.log (pwLength);
  }
  else {
    alert ("Please use characters between 8-24.");
    return false;
  };
var pwCaps 
  pwCaps = confirm("Would you like to include uppercase letters?")
  if (confirm){
    console.log (pwCaps);
};
var pwSpec 
  pwSpec = confirm("Would you like to include special characters?")
  if (confirm){
    console.log (pwSpec);
  };
  //Creating the length, case style, and character inclusion of the password based on the above variables

【问题讨论】:

  • 你得出结论了吗?

标签: javascript variables passwords generator prompt


【解决方案1】:

你可以用这个

function checkPassStrength(pass){

    let passwordVariations = {
        length: pass.length >= 8,
        digits: /\d/.test(pass),
        lower: /[a-z]/.test(pass),
        upper: /[A-Z]/.test(pass),
        nonWords: /\W/.test(pass),
        strength: 'Weak',
        progress: 10
    }

    let variationCount = 0;
    for (var check in passwordVariations) {
        variationCount += (passwordVariations[check] === true) ? 1 : 0;
    }

    if (variationCount === 5) {
        passwordVariations.progress = variationCount * 20
        passwordVariations.strength = "Excellent"
        return passwordVariations;
    }
    if (variationCount === 4) {
        passwordVariations.progress = variationCount * 20
        passwordVariations.strength = "Good"
        return passwordVariations;
    }
    if (variationCount === 3) {
        passwordVariations.progress = variationCount * 20
        passwordVariations.strength = "Average"
        return passwordVariations;
    }
    if (variationCount <= 2) {
        passwordVariations.progress = variationCount * 20
        passwordVariations.strength = "Weak"
        return passwordVariations;
    }
}

let result = checkPassStrength('Pass@123')
console.log(result)

【讨论】:

    【解决方案2】:

    让我们将您的问题分为两个主要部分。

    1. 连接数组并从中选择随机元素
    2. 条件连接

    连接数组集

    首先,假设您希望将所有字符都包含在密码模式中,因此您只需将所有字符集与Array#concatspread syntax (spread operator) 更优雅的方式结合起来 在 ES6+ 中可用。

    我将采用第二种方法,其结果将是这样的(不是很简单吗?):

    allowedCharacters = [...lower, ...num, ...caps, ...spec]
    

    然后您只需通过选择随机索引从数组中选择随机元素。因此,使用Math.random() * allowedCharacters.length 可以轻松实现,其中 Math.random() 将生成一个随机数(在0-1 的范围内,还包括0),allowedCharacters.length 是长度我们的allowedCharacter 数组。由于上一次计算的结果是十进制的,所以我们需要使用Math.floor来得到一个整数(整数)。所以这个计算的乘积会给我们一个组合数组中的随机索引。

    上面的最终输出将是:

    Math.floor(Math.random() * allowedCharacters.length)
    

    这里唯一剩下的是基于提供的密码长度的迭代。它可以通过传统的for 循环轻松实现。

    所以最后会是这样的:

    const caps = ["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 lower = ["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 num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    const spec = ['@', '%', '+', '', '/', "'", '!', '#', '$', '^', '?', ':', ',', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.']
    const allowedCharacters = [...lower, ...num, ...caps, ...spec]
    
    function createPassword(length) {
      let password = ''
    
      for (let i = 0; i < length; i++) {
        password += allowedCharacters[Math.floor(Math.random() * allowedCharacters.length)]
      }
    
      return password
    }
    
    const button = document.getElementById('generate')
    
    button.addEventListener('click', function(event) {
      event.preventDefault()
      const input = document.getElementById('length')
    
      if (input.value > 0) {
        console.log('Generated password is: ', createPassword(input.value))
      } else {
        console.log('Enter the valid positive number!')
      }
    })
    <form>
      <input type="number" id="length" placeholder="enter the length of desired password" min="1" />
      <button id="generate">generate</button>
    </form>

    条件连接

    但是您想从所需的字符集中获取项目,因此您可以使用ternary operator 使您的连接成为条件。我们可以简单地将真值或假值传递给我们之前实现的函数,然后确定是否包含每组字符的条件。

    例如,假设我们想知道使我们的下层数组连接有条件。假设lowerIncluded 是我们的条件,所以当它是true 时,我们会将较低的数组添加到我们的allowedCharacters 数组中,当它是false 时,我们将添加一个空数组(它不会将任何内容附加到我们的最终数组)。

    会是这样的:

    allowedCharacters = [...(lowerIncluded ? lower : [])]
    

    所以你的最终代码应该是这样的:

    const caps = ["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 lower = ["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 num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    const spec = ['@', '%', '+', '', '/', "'", '!', '#', '$', '^', '?', ':', ',', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.']
    
    
    function createPassword(length, lowerIncluded, capsIncluded, numIncluded, specIncluded) {
      let password = ''
      const allowedCharacters = [...(lowerIncluded ? lower : []), ...(numIncluded ? num : []), ...(capsIncluded ? caps : []), ...(specIncluded ? spec : [])]
      const allowedCharactersLength = allowedCharacters.length
    
      if (allowedCharactersLength > 0) {
        for (let i = 0; i < length; i++) {
          password += allowedCharacters[Math.floor(Math.random() * allowedCharactersLength)]
        }
    
        return password
      } else {
        return "You didn't select any allowed character set!"
      }
    }
    
    
    const button = document.getElementById('generate')
    
    button.addEventListener('click', function(event) {
      event.preventDefault()
      const input = document.getElementById('length')
      const lowerCharacters = document.getElementById('lowerCharacters')
      const capsCharacters = document.getElementById('capsCharacters')
      const numCharacters = document.getElementById('numCharacters')
      const specCharacters = document.getElementById('specCharacters')
    
      if (input.value > 0) {
        console.log('Generated password is: ', createPassword(input.value, lowerCharacters.checked, capsCharacters.checked, numCharacters.checked, specCharacters.checked))
      } else {
        console.log('Enter the valid positive number!')
      }
    })
    <form>
      <input type="number" id="length" placeholder="enter the length of desired password" min="1" />
      <button id="generate">generate</button>
      <div>
        <label for="lowerCharacters">lower</label>
        <input id="lowerCharacters" type="checkbox" checked/>
        <label for="capsCharacters">caps</label>
        <input id="capsCharacters" type="checkbox" checked/>
        <label for="numCharacters">num</label>
        <input id="numCharacters" type="checkbox" checked/>
        <label for="specCharacters">spec</label>
        <input id="specCharacters" type="checkbox" checked/>
      </div>
    </form>

    注意:这个实现不是最好的,甚至不是最聪明的方式,所以它只是为了简单和更多的说明而存在,所以它会让你了解在你的场景中应该做什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多