1
votes

I was following the basic React 'tic tac toe tutorial' and understood most of what was happening.

However when I got to the second part I ran into something I didn't quite understand, and nor could my friends really tell me how it worked.

the tic tac toe game has a history variable. this variable contains an array of a square array. (So instances of the playing field that is made up of squares).

history = [{
squares: [
  null, null, null,
  null, null, null,
  null, null, null,
]},{
squares: [
  null, null, null,
  null, 'X', null,
  null, null, null,
]},// ...]

Now in the tutorial this piece of code is written:

    const moves = history.map((step, move) => {
  const desc = move ?
    'Go to move #' + move :
    'Go to game start';
  return (
    <li>
      <button onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );
});

I get what it does, but my question is where do the step and move parameters come from? And also what exactly is the difference between step and move in this example? wouldn't one parameter suffice? I tried looking more closely at the map function, but it doesn't really give me any clarity for this specific example!

Link to full code: https://codepen.io/gaearon/pen/gWWZgR?editors=0010

Link to full tutorial (Chapter Storing a History introduces this code): https://reactjs.org/tutorial/tutorial.html

Thanks!

2
have you read Array#map documentation at all? map callback function takes up to three arguments, function callback(currentValue, index, array) - so, step is currentValue, and move is indexJaromanda X

2 Answers

2
votes

W3schools documentation here is a little simpler for me to read. Es6 introduced arrow functions so the syntax looks a little bit different, but under the hood it's the same.

The map function can take up to three arguments for currentValue, index, and array.The step and move parameters line up with currentValue and index. Since there's no third argument array is dropped.

0
votes

The 'step' is the array entry representing a specific entry into the history array. The 'move' is the index of the array pointing to 'step'. In other words, they form a pair such that we have


    history[move] = step

in the context of the 'tic tac toe tutorial'. They are coming from the specified syntax of the map method of array in JavaScript.

This is why you have to put both 'step' and 'move' there as parameters when using the array map method even though you don't use 'step' in the code. You can name them differently, though.

Normally, you would need to use 'step' for useful processing. However, in this specific case, only the index info 'move' is used to label the starting play differently and there is no use of 'step'.