【问题标题】:React Tutorial history map (step, move)React Tutorial 历史地图(step、move)
【发布时间】:2019-01-03 05:05:12
【问题描述】:

在“显示过去的动作”部分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>
      );
    });

这段代码似乎首先将一个内置变量“step”映射到变量“move”,然后才具有这个 Python 逻辑:

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

作为熟悉Python但不熟悉javascript的人,能否解释一下:

1) "step" 变量没有分配到任何地方,而且我无法在 Google 上搜索内置的 step 变量,那么 "step" 是如何分配给游戏移动数的呢?

2) 这个语法背后的逻辑是什么:(step, move) 意思是先 map step 进入 move,然后执行一个 lambda 函数?首先,第一个“map step into move”部分对我来说没有意义。

【问题讨论】:

    标签: javascript python reactjs


    【解决方案1】:

    JavaScript Array map() 函数具有以下语法:

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

    在这种情况下,step 变量是由 map 函数迭代的 history 数组的当前元素的 move 变量是当前元素的index

    通常您使用 map 函数根据原始数组返回一个新数组。在这种情况下,他们正在迭代移动历史并根据历史创建一个新的 HTML &lt;btn&gt; 元素数组。

    您可以像这样使用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>
        );
    });
    

    【讨论】:

    • 有人应该 ping 教程的家伙,因为将历史记录的每个值命名为“步骤”非常令人困惑.. currentValue 应该标记为“squares”,索引应该标记为“step”而不是 currentValue 作为“step " 并索引为 "move"
    • @user3180 你可以!创建一个你认为更容易理解的 PR here
    • 您甚至可能会争辩说在这里遍历历史完全没有必要,因为我们没有在 map 函数中使用历史中的任何内容。我认为一个简单的 for 循环到历史长度就足够了。
    【解决方案2】:

    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 元素。这里没有“map step into move”的概念。此外,move 只是数组中 step 的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2021-10-24
      • 2017-06-11
      相关资源
      最近更新 更多