【发布时间】:2019-07-11 19:16:18
【问题描述】:
有没有办法使用 typescript 生成一个包含 40 个随机符号的随机字符串?
【问题讨论】:
标签: angular typescript typescript2.0
有没有办法使用 typescript 生成一个包含 40 个随机符号的随机字符串?
【问题讨论】:
标签: angular typescript typescript2.0
这取自我们的一位开发人员编写的方法。可能这会有所帮助。我已经为你修改了。
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);
【讨论】:
其实不是 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);
【讨论】: