【问题标题】:Splice function on an array of objects对象数组上的拼接函数
【发布时间】:2019-10-16 03:02:42
【问题描述】:

我正在做一个 react/javascript 练习,但在理解 splice() 的使用时遇到了一些麻烦。 我有 8 张牌,我需要将 4 张牌随机分配给 2 名玩家。现在一切正常,但我不明白let randPokemon = hand2.splice(randIndex, 1)[0]; 行末尾的[0]

这里是完整的代码:

import React, { Component } from "react";
import Pokedex from "./Pokedex";

class Pokegame extends Component {
  static defaultProps = {
    pokemon: [
      { id: 4, name: "Charmander", type: "fire", experience: 62 },
      { id: 7, name: "Squirtle", type: "water", experience: 63 },
      { id: 11, name: "Metapod", type: "bug", experience: 72 },
      { id: 12, name: "Butterfree", type: "flying", experience: 178 },
      { id: 25, name: "Pikachu", type: "electric", experience: 112 },
      { id: 39, name: "Jigglypuff", type: "normal", experience: 95 },
      { id: 94, name: "Gengar", type: "poison", experience: 225 },
      { id: 133, name: "Eevee", type: "normal", experience: 65 }
    ]
  };

  render() {
    let hand1 = [];
    let hand2 = [...this.props.pokemon];

    while (hand1.length < hand2.length) {
      let randIndex = Math.floor(Math.random() * hand2.length);
      let randPokemon = hand2.splice(randIndex, 1)[0];
      hand1.push(randPokemon);
    }

    console.log(hand1);
    console.log(hand2);

    return (
      <div className="Pokegame">
        <h1>Pokegame!</h1>
      </div>
    );
  }
}

export default Pokegame;

我了解(如果我错了,请纠正我)splice() 函数可以采用 2 个或更多参数:第一个是指示添加/删除项目位置的索引,第二个是项目数添加/删除,下一个参数是我们要添加的项目(但我在这里不使用它,因为我只想删除选定的项目并将其添加到第一手)。

现在在这种情况下,我很难理解 [0] 是如何工作的,或者它为什么会出现在这里......

【问题讨论】:

  • 这是因为 splice 返回一个数组并且您想要第一项。这就是为什么 [0].
  • @JackBashford 我能问你编辑标签的原因吗?

标签: javascript arrays reactjs object ecmascript-6


【解决方案1】:

splice-方法在数组中添加或删除项目。它还总是返回一个数组对象,因此[0] 是访问该数组中由 splice 创建/修改的第一个元素。

【讨论】:

    【解决方案2】:

    如果您查看splice reference,您会发现它实际上返回了一个由操作删除的项目数组。

    所以在这种情况下,它会从随机索引处的hand2 数组中删除一个口袋妖怪,并返回一个包含一项的数组。

    [0] 将该项目从数组中取出并放入 randPokemon 变量中。

    【讨论】:

      【解决方案3】:

      因为splice 总是返回一个数组——[0] 提取第一个(也是唯一一个)元素。您可以使用解构来实现相同的目的:

      let [randPokemon] = hand2.splice(randIndex, 1);
      

      【讨论】:

        【解决方案4】:

        根据MDNsplice() 的返回值是由从数组中移除的元素组成的数组。

        返回值

        包含已删除元素的数组。如果仅删除一个元素,则返回一个包含一个元素的数组。如果没有元素被移除,则返回一个空数组

        它只是获取数组中已删除元素的一种方法。 hand2.splice(randIndex, 1) 将返回从数组中删除的元素。所以在这种情况下,只有 1 个元素,所以 [0] 将获得第一个元素。

        【讨论】:

        • 非常感谢您的回答!
        【解决方案5】:

        Array.splice() 为您提供新的拼接数组。即使数组中只有一个值,它仍然是一个数组,所以要访问变量,你可以使用 [0]。

        【讨论】:

          猜你喜欢
          • 2021-06-01
          • 2022-11-20
          • 2017-06-11
          • 1970-01-01
          • 2018-12-02
          • 1970-01-01
          • 2020-10-15
          • 2020-12-25
          • 2020-11-09
          相关资源
          最近更新 更多