在列表的单词中随机替换字符



我写了一个函数-"在给定的列表中随机。为了隐私和方便起见,我在这里使用了一个简单的列表。但输出不是我喜欢的答案。

例如:如果我输入";硬盘"。。。输出应该是ha dd-sk或-a-dd-sk或其他

我将非常感谢你的帮助。

const words = ['harddisk', 'laptop'];
let count, i = 0;
let wordsLength = words[i].length;
let splitted = words[i].split('');
let incompleteWords = '';

function convertToIncomplete(words) {
while (count < words[i].length / 2) {
let incompleteWords = Math.floor(Math.random() * wordsLength); //create new index
return incompleteWords;
}
}
let Words = prompt("enter your word : ");
//alert(convertToIncomplete(Words));
console.log(convertToIncomplete(Words));

这个函数只是将"-"随机插入给定列表中定义的单词

试试这个代码:

function convertToIncomplete(word){
const numberOfDashes = Math.floor(Math.random()*(word.length));
const places = [];

while(places.length < numberOfDashes){
const current = Math.floor(Math.random()*(word.length));
if(places.includes(current)) continue;
places.push(current);    
}

let newWord = word;
for(let i=0;i<places.length;i++){
newWord = newWord.substring(0, places[i])+'-'+newWord.substring(places[i]+1);
}
return newWord;
}

let Words = prompt("enter your word : ");
//alert(convertToIncomplete(Words));
console.log(convertToIncomplete(Words));

最新更新