Bil*_*man 3 javascript shuffle
我正在尝试做一些相当简单的事情,但我的代码看起来很糟糕,我确信有更好的方法可以在javascript中执行操作.我是javascript的新手,我正在努力改进我的编码.这只是感觉非常混乱.
我想做的就是随机更改网页上某些单词的顺序.在python中,代码看起来像这样:
s = 'THis is a sentence'
shuffledSentence = random.shuffle(s.split(' ')).join(' ')
Run Code Online (Sandbox Code Playgroud)
然而,这是我设法用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);
}
Run Code Online (Sandbox Code Playgroud)
你能帮我简化一下吗?
Anu*_*rag 11
几乎类似于python代码:
var s = 'This is a sentence'
var shuffledSentence = s.split(' ').shuffle().join(' ');
Run Code Online (Sandbox Code Playgroud)
为了使上述工作,我们需要向Array添加一个shuffle方法(使用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;
};
Run Code Online (Sandbox Code Playgroud)