shuffle - Shuffling words in a sentence in javascript (coding horror - How to improve?) -


i'm trying simple, code looks terrible , there better way things in javascript. new javascript, , trying improve coding. feels messy.

all want randomly change order words on web page. in python, code this:

s = 'this sentence' shuffledsentence = random.shuffle(s.split(' ')).join(' ') 

however, monstrosity i've managed produce in 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 create temporary array of objects make sorting easier     var temparray = new array(splitcontent.length);      (var = 0; < splitcontent.length; i++) {         //create object can assigned random number sorting         var tmpobj = new object();         tmpobj.sortvalue = math.random();         tmpobj.string = splitcontent[i];         temparray[i] = tmpobj;            }      temparray.sort(mysort);      //copy strings original array     (i = 0; < splitcontent.length; i++) {         splitcontent[i] = temparray[i].string;     }      content = splitcontent.join(' ');            //the result     $(this).text(content);        } 

can me simplify things?

almost similar python code:

var s = 'this sentence' var shuffledsentence = s.split(' ').shuffle().join(' '); 

for above work, need add shuffle method array (using fisher-yates).

array.prototype.shuffle = function() {     var = this.length;     if (i == 0) return this;     while (--i) {         var j = math.floor(math.random() * (i + 1 ));         var = this[i];         var b = this[j];         this[i] = b;         this[j] = a;     }     return this; }; 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -