使用 Angular 6 生成随机字符串

Pet*_*zov 0 typescript typescript2.0 angular

有没有办法使用打字稿生成带有 40 个随机符号的随机字符串?

smt*_*512 10

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

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);
Run Code Online (Sandbox Code Playgroud)


Ser*_*ell 5

实际上不是关于 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');
Run Code Online (Sandbox Code Playgroud)

或者

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

import randomString from 'randomstring';
const result = randomString.generate(40);
Run Code Online (Sandbox Code Playgroud)