Skip to content

如何随机生成包含两位连续相同数字的四位验证码思路整理 #617

Description

@babysodme

如何随机生成包含两位连续相同数字的四位验证码思路整理?

最初思路:随机生成三个数字——通过操作数组游标使用concat()方法在操作游标后面加一个相同的值创建并返回一个新数组。

结果:不成立啦~原因是数字根本不可以当作数组直接操作;

  • 转换思路:将数字转换为字符串用同方法操作;并用push()方法测试;

结果:也是不成立;

  • 转换思路:去犀牛书看了字符串的使用里面有匹配查找和替换;

结果:成立。将数字转为字符串使用replace()方法替换内容在转换为数字。

  • 代码部分
  var threeNumber = String(Math.round((Math.random() * 899)+100));
  // 随机生成一个三位数字并转换为字符串
  var sub = threeNumber[Math.round(Math.random() * 2)];
  // 通过随机游标定义需要查找并替换的变量
  var verifyCode = Number(threeNumber.replace (sub,sub+sub));
  // 使用repalce()查找并替换内容同时将字符串转换为数字;
  console.log(verifyCode);

收获

  1. 之前隐约记得字符串可以像数组一样操作,结果不这样,在回头看书发现写着字符串可以当做只读数组,那意思就是无法像数组一样写入了;
  2. 认识并使用了repalce()方法同时知道了更多的匹配、匹配位置等操作字符串的方法;
  3. 写收获的时候发现数组的join()方法可以将数组转化为字符串,尝试了一下又找到了splice()方法可以在数组指定位置插入元素;惊喜之余然后下面的代码就出现了。

(function(){
var random = [Math.round((Math.random() * 8)+1),Math.round((Math.random() * 8)+1),Math.round((Math.random() * 8)+1)];
// 生成长度为2的随机数组 
sub = Math.round((Math.random() * 1)+1);
// 生成0-2的随机数
random.splice(sub , 0 , random[sub]);
// 在数组的随机位置后面插入元素
verifyCode = Number(random.join(""));
// verifyCode变量代表验证码
return verifyCode;
})(); 

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions