在“显示过去的动作”部分here中,我们有以下代码:
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>
);
});
在本质上具有以下Python逻辑之前,这段代码似乎是先将内置变量“ step”映射到变量“ move”:
const moves = [lambda move: const desc = move ... for move in history]
作为熟悉Python但不了解javascript的人,您能解释一下吗?
1)“ step”变量没有分配到任何地方,并且我无法在Google内置的step变量中进行搜索,那么“ step”如何分配给游戏移动次数?
2)此语法背后的逻辑是什么:(步进,移动)意味着首先将地图步进到移动中,然后执行lambda函数?首先,对我而言,第一个“迈出第一步的地图”部分没有意义。
答案 0 :(得分:2)
JavaScript Array map()函数具有以下语法:
array.map(function(currentValue, index, arr), thisValue)
在这种情况下,step
变量是由map函数迭代的history
数组的当前元素的 value 。 move
变量是当前元素的 index 。
通常,您使用map函数根据原始数组返回新数组。在这种情况下,他们要遍历移动的历史并根据历史创建新的HTML <btn>
元素数组。
您可以使用forEach
来完成相同的操作,
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>
);
});
答案 1 :(得分:0)
map
是数组上可用的函数。它用于将数组中的所有元素映射到其他对象。例如,如果您想将数组中的所有元素加倍,则可以:
const arr = [1, 2, 3, 4];
const newArr = arr.map(element => element * 2)
console.log(newArr);
等效于
const arr = [1, 2, 3, 4];
const newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i] * 2);
}
console.log(newArr);
在您的情况下,history
是一个数组。然后,您将每个step
(仅history
的每个元素)映射到li
React元素。这里没有“地图踏入”的概念。另外,move
只是数组中step
的索引。