Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - 如何改组数组? [重复](How can I shuffle an array? [duplicate])

Possible Duplicate:(可能重复:)

I want to shuffle an array of elements in JavaScript like these:(我想改写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]   ask by Anshul translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the modern version of the Fisher–Yates shuffle algorithm :(使用现代版本的Fisher-Yates随机播放算法 :)

/** * 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) version(ES2015(ES6)版本) /** * 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; } Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.(但是请注意,截至2017年10月,将变量与解构分配交换会导致严重的性能损失。) Use(使用) var myArray = ['1','2','3','4','5','6','7','8','9']; shuffle(myArray);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...