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.
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>
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With