我是一个 javascript 初学者,我遇到了一个问题。我有一个 javascript 函数来打乱字符串中的字符,从而保持单词长度和空格就像原始句子一样。
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
String.prototype.shuffle = function () {
// pass to shuffleArray an array of all non-whitespace characters:
const randomChars = shuffleArray([...this.replace(/\s+/g, '')]);
let index = 0;
// `\S` matches any non-whitespace character:
return this.replace(/\S/g, () => randomChars[index++]);
}
console.log(
`The keys are under the mat`
.shuffle()
);
我想添加的是向函数添加一个具有定义字母的变量,该变量应该在随机播放过程中跳过。现在我们有了,即:
钥匙在垫子下面
atd meey eke nTshr hau ert
最终结果:
ahd meey ere nTshr ahu ekt
我能想到的最佳解决方案如下:
有很多方法可以解决这个问题,但使其高效取决于一系列因素,例如特定的输入字符串、它的长度以及排除数组中的字符数。
我会考虑使用 .split() 方法,如下所示:w3schools .split()
希望这有帮助。
你可以取一串剩下的字符,构建两个正则表达式进行收集和替换。
function shuffleArray(array) {
for (let i = array.length - 1; i; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
String.prototype.shuffle = function (keep = '') {
keep += '\\s';
const
chars = this.replace(new RegExp(`[${keep}]`, 'gi'), ''),
randomChars = shuffleArray([...chars]);
let index = 0;
return this.replace(new RegExp(`[^${keep}]`, 'gi'), () => randomChars[index++]);
};
console.log('The keys are under the mat');
console.log('The keys are under the mat'.shuffle());
console.log('The keys are under the mat'.shuffle('hr'));