如何快速让一个数组乱序,写出来

在前端开发中,如果你想要快速让一个数组乱序(也叫做洗牌算法或 Fisher-Yates 洗牌算法),你可以使用 JavaScript 的以下代码:

function shuffleArray(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // 当仍剩元素需要混洗时
    while (0 !== currentIndex) {

        // 选取一个剩余元素...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // 并与当前元素交换。
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

// 使用示例
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
shuffleArray(myArray);
console.log(myArray);

这段代码使用了 Fisher-Yates 洗牌算法,它是一个高效且能够产生无偏的随机排列的算法。在这个算法中,我们从数组的末尾开始,每次迭代都随机选择一个在当前范围内的索引,并与当前索引处的元素进行交换。这样,每个元素都有机会被移动到新的位置,从而确保最终的排列是随机的。

posted @ 2025-01-13 09:09  王铁柱6  阅读(38)  评论(0)    收藏  举报