Javascript 如何洗牌阵列?

Javascript 如何洗牌阵列?,javascript,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] 使用: ES2015(ES6)版本 然而,请注意,截至2017年10月,与交换变量会导致显著的性能损失 使用 实现原型 使用Object.defineProperty()我们还可以将此函数作为数组的原型方法来实现,而不必在循环中显示它,例如

我想在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]
使用:

ES2015(ES6)版本 然而,请注意,截至2017年10月,与交换变量会导致显著的性能损失

使用 实现原型 使用
Object.defineProperty
()我们还可以将此函数作为数组的原型方法来实现,而不必在循环中显示它,例如
for(i in arr)
。以下命令将允许您调用
arr.shuffle()
来洗牌数组
arr

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;
    }
});
您可以使用(改编自的代码):


关于stackoverflow,已经回答了多次。还有一个问题:这是一个很好的数据和数学资源。一行怎么样?返回的数组被洗牌。arr1.reduce((a,v)=>a.splice(Math.floor(Math.random()*a.length),0,v)和&a,[])@VitaliPom不使用sort()和random()。排序不期望随机结果,结果可能不一致。微软的浏览器投票就是因为这个原因。@brunettdan我写了一行代码,它不使用拼接,速度更快:
arr1.reduceRight((p,v,I,a)=>(v=I?~~(Math.random()*(I+1)):I,v-I?[a[v],a[I]=[a[I],a[v]]:0,a),a)
;另外,请查看。是否要详细说明闭包编译器是如何加快速度的?第一个答案似乎有一个bug。大约每运行15次,我就会得到一个额外的
undefined
列。为什么不使用random+Array.prototype.sort?这比两个答案都简单,代码也更少。@Volter9:因为分布不均匀。杰夫·阿特伍德关于这个算法的帖子真的很有趣。我想知道为什么它是这样实现的。这个方法(以及下面的方法)都修改了原始数组。这没什么大不了的,但是如何称呼它的例子有点奇怪。@Michael+1指出重新分配是不必要的。事实上,这是有误导性的,可能应该是在这个评论线程中指出的第一件事。我发现ES6交换速度较慢(一旦我让它工作起来。你必须在[--之前有一个分号,这就更有理由总是使用它们。)@trlkly:ES2015变体由于使用了解构赋值,速度会慢一些。希望引擎能很快对其进行优化。@RobG const是一个完美的选择,因为它是块范围的,不同于var,并且在每次迭代后都会重新声明。let也可以工作,但由于j没有改变块范围内的值,因此对于块const来说是更好的选择
/**
 * 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;
}
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
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;
    }
});
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;
}