Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Tutorial history map (step, move)

In the "Showing the Past Moves" section here, we have the below code:

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>
      );
    });

This code seems to be first mapping a built in variable "step" to variable "move", before essentially having this Python logic:

const moves = [lambda move: const desc = move ... for move in history]

As someone who is familiar with Python but not javascript, can you explain:

1) "step" variable is not assigned anywhere, and I haven't been able to google a built in step variable, so how is "step" getting assigned to the number of game moves?

2) What is the logic behind this syntax: (step, move) meaning first map step into move, then execute a lambda function? Primarily, the first 'map step into move' part doesn't make sense to me.

like image 824
user3180 Avatar asked Jan 03 '19 05:01

user3180


Video Answer


1 Answers

The JavaScript Array map() function has the following syntax:

array.map(function(currentValue, index, arr), thisValue)

In this case, the step variable is the value of the current element of the history array being iterated by the map function. The move variable is the index of the current element.

Typically you use the map function to return a new array based upon the original array. In this case, they are iterating the history of moves and creating a new array of HTML <btn> elements based upon the history.

You could accomplish the same using forEach like so:

let moves = [];
history.forEach((step, move) => {
    const desc = move ?
          'Go to move #' + move :
          'Go to game start';
    moves.push(
        <li>
            <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
    );
});
like image 125
Ben Beck Avatar answered Sep 22 '22 06:09

Ben Beck