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 (skipChars = []) { // 把跳过字符转成Set,提升判断效率 const skipSet = new Set(skipChars); // 收集所有需要参与洗牌的字符:非空格且不在跳过集合里 const shuffledCandidates = shuffleArray( [...this].filter(char => char !== ' ' && !skipSet.has(char)) ); let index = 0; // 遍历原字符串,空格/跳过字符直接保留,其他用洗牌后的字符填充 return [...this].map(char => { if (char === ' ' || skipSet.has(char)) { return char; } return shuffledCandidates[index++]; }).join(''); } // 测试:指定跳过['h','r'] console.log( `The keys are under the mat` .shuffle(['h','r']) );
关键修改说明:
- 新增
skipChars参数,默认是空数组,支持传入需要保留原位置的字符集合 - 用
Set存储跳过字符,判断字符是否需要跳过的效率更高 - 筛选可洗牌字符时,排除空格和跳过字符,只对剩下的字符执行洗牌操作
- 遍历原字符串时,遇到空格或跳过字符直接返回原字符,其他字符从洗牌后的数组中依次取元素填充
这样处理后,指定的h和r会完全保留在原位置,其他字符在非跳过位置随机洗牌,符合预期效果。
内容的提问来源于stack exchange,提问作者Marcin MaG
相关产品推荐
相关产品推荐

