如何改组数组?\[重复\]

JavaScript

GO小胖

2020-03-13

我想改写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]

第1376篇《如何改组数组?\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
西门小小 2020.03.13

您可以使用Fisher-Yates Shuffle此网站改编的代码):

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;
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android