gpt4 book ai didi

javascript - 如何打乱对象数组

转载 作者:行者123 更新时间:2023-12-02 22:47:59 25 4
gpt4 key购买 nike

我正在尝试使用 shuffle npm 模块( https://www.npmjs.com/package/shuffle-array )对对象数组进行洗牌 - 但是我收到诸如“ypeError:Object(...) is not a function”之类的错误。

   let posts = [
{
postUrl: "https://www.linkedin.com/1",
action: "Post",
profileUrl: "https://www.linkedin.com/company/1",
timestamp: "2019-10-09T09:40:05.356Z"
},
{
postUrl: "https://www.linkedin.com/2",
action: "Post",
profileUrl: "https://www.linkedin.com/company/2",
timestamp: "2019-10-09T09:40:05.356Z"
},
{
postUrl: "https://www.linkedin.com/3",
action: "Post",
profileUrl: "https://www.linkedin.com/company/3",
timestamp: "2019-10-09T09:40:05.356Z"
},
]

posts = shuffle(posts);

你能看出我错在哪里吗?或者如何重新排列这些对象?

最佳答案

对于大多数用途,最好的方法是使用 Fisher Yates/Knuth shuffle,我确信其他一些人会链接到。本文对此进行了讨论:

How to randomize (shuffle) a JavaScript array?

随机化的核心内容归结为以下内容(也可以在上述帖子中找到!):

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

// While there remain elements to shuffle...
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}

// Used like so
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);

希望这对您有所帮助!

关于javascript - 如何打乱对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com