【发布时间】:2018-09-25 11:36:18
【问题描述】:
已经在这个问题上停留了一段时间。为乒乓球游戏生成器开发 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;
【问题讨论】:
-
为什么不随机化整个数组并从中弹出对?
-
到底是什么问题?
let arr1 = ...和return ()的定义之间的所有内容都按照您的描述工作,所以问题是您的数组不包含您所说的内容,或者导入不起作用,或者返回渲染部分的反应。 -
好点 jvdh,我有点不知道该怎么做?
-
我现在已经纠正了 console.log 问题,但是我希望只是随机化他们从中获取对的数组。任何有关这方面的帮助都会很棒
标签: javascript reactjs random shuffle