5

私はかなり単純なことをしようとしていますが、私のコードはひどく見えます.javascriptで物事を行うためのより良い方法があると確信しています. 私は JavaScript が初めてで、コーディングを改善しようとしています。これは非常に面倒です。

私がやりたいのは、Web ページ上のいくつかの単語の順序をランダムに変更することだけです。Python では、コードは次のようになります。

s = 'THis is a sentence'
shuffledSentence = random.shuffle(s.split(' ')).join(' ')

ただし、これは私がjavascriptで作成した怪物です

//need custom sorting function because javascript doesn't have shuffle?
function mySort(a,b) {    
    return a.sortValue - b.sortValue;
}

function scrambleWords() {

    var content = $.trim($(this).contents().text());

    splitContent = content.split(' ');

    //need to create a temporary array of objects to make sorting easier
    var tempArray = new Array(splitContent.length);

    for (var i = 0; i < splitContent.length; i++) {
        //create an object that can be assigned a random number for sorting
        var tmpObj = new Object();
        tmpObj.sortValue = Math.random();
        tmpObj.string = splitContent[i];
        tempArray[i] = tmpObj;       
    }

    tempArray.sort(mySort);

    //copy the strings back to the original array
    for (i = 0; i < splitContent.length; i++) {
        splitContent[i] = tempArray[i].string;
    }

    content = splitContent.join(' ');       
    //the result
    $(this).text(content);      

}

物事を単純化するのを手伝ってもらえますか?

4

5 に答える 5

13

Python コードとほとんど同じです。

var s = 'This is a sentence'
var shuffledSentence = s.split(' ').shuffle().join(' ');

上記を機能させるには、 shuffle メソッドを Array に追加する必要があります ( Fisher-Yatesを使用)。

Array.prototype.shuffle = function() {
    var i = this.length;
    if (i == 0) return this;
    while (--i) {
        var j = Math.floor(Math.random() * (i + 1 ));
        var a = this[i];
        var b = this[j];
        this[i] = b;
        this[j] = a;
    }
    return this;
};
于 2010-04-27T19:59:06.967 に答える
1
String.prototype.shuffler=function(delim){
    delim=delim || '';
    return this.split(delim).sort(function(){
            return .5-Math.random()}).join(delim);
}

//単語をシャッフルするには、スペースを渡します

var s='abc def ghi jkl mno pqr stu vwx yz' alert(s.shuffler(' '))

于 2010-04-27T20:09:12.567 に答える
0

This code is untested, but it is a rough idea of an alternative approach:

function scrambleWords(text) {
  var words = text.split(' ');
  var result = "";

  while(words.length > 0) {
    if(result.length > 0) { words += " "; }
    words += words.splice(Math.abs(Math.random() * (words.length - 1)), 1);
  }

  return result;
}

Basically, the idea is to randomly splice words out of the origonal text and rebuild the string.

NOTE: splice is a little slow (rebuilds array), so if performance matters, I wouldn't suggest this as optimal, but I think the code is simplier.

UPDATE: I like the shuffle answer better that was just posted as a better solution :D

于 2010-04-27T20:02:18.637 に答える
0

sort メソッドと Math メソッドの使用:

var arr =  ["HORSE", "TIGER", "DOG", "CAT"];
function shuffleArray(arr){
  return arr.sort( () => Math.floor(Math.random() * Math.floor(3)) - 1)  
}

// every time it gives random sequence
shuffleArr(arr);
// ["DOG", "CAT", "TIGER", "HORSE"]
// ["HORSE", "TIGER", "CAT", "DOG"]
// ["TIGER", "HORSE", "CAT", "DOG"]
于 2020-09-18T09:54:20.707 に答える