首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何对数组进行混洗?

如何对数组进行混洗?
EN

Stack Overflow用户
提问于 2011-06-08 12:52:41
回答 2查看 498.3K关注 0票数 529

我想在JavaScript中打乱一个元素数组,如下所示:

代码语言:javascript
复制
[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-08 12:58:38

使用the modern version of the Fisher–Yates shuffle algorithm

代码语言:javascript
复制
/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6)版本

代码语言:javascript
复制
/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

然而,请注意,从2017年10月起,与destructuring assignment交换变量会导致显著的性能损失。

使用

代码语言:javascript
复制
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

实现原型

使用Object.defineProperty (method taken from this SO answer),我们还可以将此函数实现为数组的原型方法,而不会在for (i in arr)等循环中显示它。下面的代码将允许您调用arr.shuffle()来混洗数组arr

代码语言:javascript
复制
Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});
票数 1.1K
EN

Stack Overflow用户

发布于 2011-06-08 13:01:40

您可以使用Fisher-Yates Shuffle (改编自this site的代码):

代码语言:javascript
复制
function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}
票数 484
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6274339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档