在javascript中用句子中的单词洗牌(编码恐怖 - 如何改进?) [英] Shuffling words in a sentence in javascript (coding horror - How to improve?)
问题描述
我正在尝试做一些相当简单的事情,但我的代码看起来很糟糕,我确信有更好的方法可以在javascript中执行操作。我是javascript的新手,我正在努力改进我的编码。这只是感觉非常混乱。
I'm trying to do something that is fairly simple, but my code looks terrible and I am certain there is a better way to do things in javascript. I am new to javascript, and am trying to improve my coding. This just feels very messy.
我想做的就是随机更改网页上某些单词的顺序。在python中,代码看起来像这样:
All I want to do is to randomly change the order some words on a web page. In python, the code would look something like this:
s = 'THis is a sentence'
shuffledSentence = random.shuffle(s.split(' ')).join(' ')
但是,这是我设法用javascript生成的怪物
However, this is the monstrosity I've managed to 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 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);
}
你能帮我简化一下吗?
推荐答案
几乎与python代码类似:
Almost similar to the python code:
var s = 'This is a sentence'
var shuffledSentence = s.split(' ').shuffle().join(' ');
为了实现上述功能,我们需要为Array添加一个shuffle方法(使用 Fisher-Yates )。
For the above to work, we need to add a shuffle method to Array (using 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;
};
这篇关于在javascript中用句子中的单词洗牌(编码恐怖 - 如何改进?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!