【问题标题】:Generate random string with Angular 6 [duplicate]使用Angular 6生成随机字符串[重复]
【发布时间】:2019-07-11 19:16:18
【问题描述】:

有没有办法使用 typescript 生成一个包含 40 个随机符号的随机字符串?

【问题讨论】:

    标签: angular typescript typescript2.0


    【解决方案1】:

    这取自我们的一位开发人员编写的方法。可能这会有所帮助。我已经为你修改了。

    function makeRandom(lengthOfCode: number, possible: string) {
      let text = "";
      for (let i = 0; i < lengthOfCode; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
        return text;
    }
    let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,./;'[]\=-)(*&^%$#@!~`";
    const lengthOfCode = 40;
    makeRandom(lengthOfCode, possible);
    

    【讨论】:

      【解决方案2】:

      其实不是 TypeScript,而是 JavaScript

      你可以使用很多方法,即

      function randomString(length, chars) {
          var result = '';
          for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
          return result;
      }
      var rString = randomString(40, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
      

      导入一些现成的库,例如https://www.npmjs.com/package/randomstring 并像使用它

      import randomString from 'randomstring';
      const result = randomString.generate(40);
      

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 2015-08-16
        • 2014-02-05
        • 1970-01-01
        • 2019-04-20
        • 2017-01-06
        • 2017-04-05
        • 1970-01-01
        相关资源
        最近更新 更多