0

已经坚持了一段时间了。为乒乓球游戏生成器开发 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;
4

1 回答 1

1

我喜欢.sortMath.random

const players = ['John', 'Jack', 'Anne', 'Marry', 'Mike', 'Jessica'];

players.sort(() => 0.5 - Math.random());

const pairs = [];

// as we need at least players to form a pair
while (players.length >= 2) { 
  const pair = [players.pop(), players.pop()];

  // Current pair
  console.log('Single pair', pair);

  // Save current pair
  pairs.push(pair);
}

// All pairs
console.log('All pairs', pairs);

我猜你已经知道了,但是 random 会返回 0 到 1 之间的数字(不包括 1),所以这个排序函数会随机返回 -0.5 到 0.5 之间的数字,对数组进行洗牌。

Pop 将返回数组中的最后一项并将其从数组中删除。我们弹出两次以获得一对。

希望有帮助!


继续评论。

为了渲染它,我会创建一个组件并传递pairs给它。这是 React 必不可少的,你会经常做的事情。

import React from 'react';

component Pairs extends React.component
  renderPairs() {
    // pass pairs as prop
    return this.props.pairs.map(pair => {
      return (
        <li key={ pair.join('-') }>
          { pair.join(' vs ') }
        </li>
      )
    });
  }

  return (
    <ul>
      { this.renderPairs() }
    </ul>
  )
}

// Use it like this
// <Pairs pairs={ pairs } />
于 2018-09-25T12:24:50.363 回答