已经坚持了一段时间了。为乒乓球游戏生成器开发 React 项目。努力寻找一种解决方案来随机打乱用户输入的名称数组。它甚至不会 console.log 任何东西!非常感谢。
import React, { Fragment } from "react";
const FixturesList = playerNamesArray => {
let shuffledPlayers = [...playerNamesArray];
let arr1 = shuffledPlayers.slice(); // copy array
let arr2 = shuffledPlayers.slice(); // copy array again
arr1.sort(function() {
return 0.5 - Math.random();
}); // shuffle arrays
arr2.sort(function() {
return 0.5 - Math.random();
});
while (arr1.length) {
let player1 = arr1.pop(), // get the last value of arr1
player2 = arr2[0] === player1 ? arr2.pop() : arr2.shift();
// ^^ if the first value is the same as name1,
// get the last value, otherwise get the first
console.log(player1 + " gets " + player2);
}
return (
<Fragment>
<section>
<h1>Fixtures</h1>
</section>
</Fragment>
);
};
export default FixturesList;