javascript - 如何在 JavaScript 中使用 switch

标签 javascript switch-statement

我一直在尝试制作一个密码生成器,我有这段代码,它返回“未定义”而不是字符。该代码应该返回 16 个字符,包括数字、小写字符和大写字符。我想要这个,这样我就不用再担心自己创建密码了。

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>PassGen</title>
  <script>
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function num2lett(num) {
      switch (num) {
        case (num > 36):
          return String.fromCharCode(577 + num - 35);
          break;
        case (num > 10 && num < 37):
          return String.fromCharCode(97 + num - 11);
          break;
        case (num == 10):
          return "0";
          break;
        case (num < 10):
          return "" + num;
          break;
      }

    }

    function uuidMake() {
      var uuid = "";
      for (u = 0; u < 16; u++) {
        randNum = getRandomInt(0, 62);
        uuid += num2lett(randNum);
      }
      document.getElementById("password").innerHTML = uuid;
    }
  </script>
  <style>
    @font-face {
      font-family: "uuid_font";
      src: url("Courier Prime Code.ttf") format("TrueType");
    }
    
    body {
      background-color: #262626;
    }
    
    #password {
      font-family: "uuid_font";
      text-align: center;
      font-size: 30px;
      color: #dddddd;
      margin-top: 250px;
    }
  </style>

  <body>
    <p id="password" onclick="uuidMake();">Click Me</p>
  </body>

</html>

最佳答案

这不是 switch 的良好用例。使用 ifelse 语句。

switch 语句中的 case 是您要switch 的表达式的特定可能值。例如,人们可能会写这样的内容:

switch (n) {
    case 1:
        // things to do when n is 1
        break;
    case 3:
    case 4:
        // things to do when n is 3 or 4
        break;
    default:
        // things to do when n is neither 1, 3, nor 4
}

case 语句不能是值范围。也不建议使用表达式作为 case —— 它不是无效,但它可能也不会达到您的预期。

关于javascript - 如何在 JavaScript 中使用 switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397001/

相关文章:

C - 战舰,随机放置

java - 可以在 switch 的一个 case 语句中进行两次比较吗?

javascript - 如果我的用户有 ie6 该怎么办

javascript - 使用 Js 在 html 表单中输入正确的密码时导航到 url

javascript - 可见窗口高度而不是 $(window).height();

javascript - 如何使用 javascript 创建监听器

Swift:似乎不允许比较字符串?用一个字符串?

c++ - 在程序中一起使用 If 和 Switch 语句

Javascript switch 语句 - default first OK?

javascript - 无需对任何 DOM 元素执行用户操作即可触发文件输入字段