在 javascript 中打乱句子中的单词(编码恐怖 - 如何改进?)

2023-12-10

我正在尝试做一些相当简单的事情,但我的代码看起来很糟糕,我确信有更好的方法可以用 javascript 来做事情。我是 javascript 新手,正在努力改进我的编码。这只是感觉非常混乱。

我想做的就是随机更改网页上某些单词的顺序。在 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);      

}

你能帮我简化事情吗?


与python代码几乎类似:

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

为了使上述工作正常进行,我们需要向 Array 添加一个 shuffle 方法(使用费希尔-耶茨).

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;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 javascript 中打乱句子中的单词(编码恐怖 - 如何改进?) 的相关文章

随机推荐