简体   繁体   English

在单词中随机排列字母。 javascript

[英]Shuffle letters in word. javascript

I need to shuffle the letters in a word, but I can't change the position of the first and last letters. 我需要将单词中的字母随机排列,但不能更改首字母和最后一个字母的位置。

And this is my function for shuffelWord: 这是我的shuffelWord函数:

function shuffelWord(word) {
        var shuffledWord = '';
        word = word.split('');
        console.log("word", word);
        while (word.length > 0) {
            shuffledWord += word.splice(word.length * Math.random() << 0, 1);
        }
        return shuffledWord;
    }

What I am doing wrong? 我做错了什么?


You can so something like: 您可以这样:

 function shuffelWord(word) { word = word.split(''); //Remove the first and the last letter let first = word.shift(); let last = word.pop(); //Shuffle the remaining letters for (let i = word.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [word[i], word[j]] = [word[j], word[i]]; } //Append and return return first + word.join("") + last; } let test = shuffelWord('javascript'); console.log(test); 

Instead of taking all the word's letters in an array, exclude the first and last from that. 与其将所有单词的字母排在一个数组中,还不包括它的第一个和最后一个。 Also use another variable for that array, so that you still have access to the original word and can append the first and last character again: 还可以对该数组使用另一个变量,以便您仍然可以访问原始单词,并且可以再次追加第一个和最后一个字符:

function shuffelWord(word) {
    var shuffledWord = '';
    var letters = word.split('').slice(1, -1); // exclude first and last
    while (letters.length > 0) {
        shuffledWord += letters.splice(letters.length * Math.random() << 0, 1);
    }
    return word[0] + shuffledWord + word[word.length-1]; // include first and last
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM