JavaScript密码生成器创建奇怪的字符



我用javascript创建了一个简单的密码生成器。

当您单击页面上的按钮时,它会为您创建一个密码并将其显示在下方。 此密码生成器创建一个包含以下内容的字符串:

来自 A-Z 的 8 个随机字母。

2 个从 0-9 的随机数。

字符串数组中的 1 个随机特殊字符。(请参阅数组"字符")。

但是,在您单击该按钮几次后,最终将生成一个包含 2 个特殊字符的密码,其中包含"Â"。我很困惑,因为这个字符不在字符数组中。

为什么会这样,无论如何都要告诉JS不要特别包含该字符?

function myFunction() {
// create initial arrays.
a = [];
var chars = ['#', '%', '£', '!', '?', '&'];
for (var i = 97; i <= 122; i++) {
a[a.length] = String.fromCharCode(i).toUpperCase();
// create random letters.
var one = a[Math.floor(Math.random() * a.length)];
var two = a[Math.floor(Math.random() * a.length)];
var three = a[Math.floor(Math.random() * a.length)];
var four = a[Math.floor(Math.random() * a.length)];
var five = a[Math.floor(Math.random() * a.length)];
var six = a[Math.floor(Math.random() * a.length)];
var seven = a[Math.floor(Math.random() * a.length)];
var eight = a[Math.floor(Math.random() * a.length)];
// create random numbers.
var int1 = Math.floor(Math.random() * 10);
var int2 = Math.floor(Math.random() * 10);
var ints = int1.toFixed(0) + int2.toFixed(0);
var intsDecimal = int1.toFixed(0) + "." + int2.toFixed(0);
// create random characters, based on array (chars).
var randChar = chars[Math.floor(Math.random() * chars.length).toFixed(0)];
// create variable moving all letters, numbers and characters together.
var c = one + two + three + four + five + six + seven + eight + ints + randChar;
}
// display variable c.
document.getElementById('userPass').innerHTML = c;
}
<p>Using simple JS to create a random password.</p>
<button onclick="myFunction()">CLICK</button>
<h4>Your password is:</h4>
<h3 id="userPass"></h3>

根据需要使用特定模式(如 3 个大写、3 个小写、特殊字符和所有长度的数字)生成密码。

const generatePassword = (str, limit) =>{
let password = "";
for (let i = 1; i <= limit; i++) {
let char = Math.floor(Math.random()
* str.length);
password += str.charAt(char)
}
return password;
}
let password = () => {
let ucstr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let lcstr = 'abcdefghijklmnopqrstuvwxyz';
let digitstr = '0123456789';
let spstr = '@#$';

const password = generatePassword(ucstr, 5) + generatePassword(lcstr, 3)  + generatePassword(digitstr, 2)  + generatePassword(spstr, 2);
return password;
}
console.log("Your Password us ===> ", password());

示例输出为AXTSFadsf34#@

最新更新