javascript - 我使用 JavaScript 函数生成带有大写小写符号和数字的强密码,但它得到只读错误
问题描述
错误:TypeError:无法分配给字符串 'Wr9[85(W|V,s/BdL^' 的只读属性 '16'
但是我使用代码将其定义为下面的可写检查脚本,将代码放入 zapier 脚本时出现此错误:
function getRandomChar(str) {
return str.charAt(Math.floor(Math.random() * str.length));
}
function shuffle(array) {
var currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function generatePHelper(groups, length) {
return function() {
let pass = groups.map(getRandomChar).join('');
const str = groups.join('');
for (let i = pass.length; i <= length; i++) {
pass += getRandomChar(str)
}
return shuffle(pass);
};
}
const groups = [
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz',
'1234567890',
'!@#$%^&()_+~`|}{[]:;?><,./-='
];
const generateP = {};
Object.defineProperty(generateP, 'property1', {
writable: true,
value: generatePHelper(groups, 16)
});
alert(generateP.property1())
解决方案
在shuffle()
你得到一个字符串(只读类型),但你将它用作一个数组(可变类型)。试试这个(更改和添加的行都标有注释):
function shuffle(str) { // changed
const array = [...str]; // added
var currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array.join(''); // changed
}