Le premier type:
// code de http://caibaojian.com/js-random-string.htmlfunction makeId () {var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; pour (var i = 0; i <5; i ++) text + = possible.charat (math.floor (math.random () * possible.length)); Retour texte;}Le deuxième type: pas besoin d'entrer un jeu de caractères
fonction randomString (l) {var s = ''; var randomchar = function () {var n = math.floor (math.random () * 62); if (n <10) retourner n; // 1-10 if (n <36) String de retour.fromCharcode (n + 55); // az return String.fromCharcode (n + 61); // az} while (s.length <l) s + = randomchar (); retour s;} alert(randomstring(5))
Le troisième type: prend en charge la longueur de caractère et la collection de caractères personnalisés
fonction RandomString (len, charset) {charset = charset || 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; var RandomString = ''; for (var i = 0; i <len; i ++) {var randompoz = math.floor (math.random () * charset.length); RandomString + = charSet.Substring (Randompoz, Randompoz + 1); } return RandomString;}Appelez avec le charme par défaut [A-ZA-Z0-9] ou envoyez votre propre:
var randomvalue = randomString (5); var randomvalue = randomString (5, 'pickcharsfromthisset');
Capture d'écran de démo
Ce qui précède est un résumé de trois méthodes de création de chaînes aléatoires contenant des nombres et des lettres en JavaScript. Si vous en avez besoin, vous pouvez vous y référer et l'apprendre.