javascript - 对象数组的拼接函数

标签 javascript arrays reactjs object ecmascript-6

我正在做一个 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] 是如何工作的或者它为什么会在这里...

最佳答案

根据 MDN splice() 的返回值是由从数组中删除的元素组成的数组。

Return Value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned

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

关于javascript - 对象数组的拼接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378540/

相关文章:

javascript - Javascript 数组方法的意外行为

javascript - XHR 使用或不使用 gdrive api 下载不同用户的公共(public) google 驱动器文件

c - 如何以编程方式获取二维数组中元素的相邻元素?

javascript - parseFloat 在附加到 ref 的 componentDidMount 函数中返回 NaN

javascript - 如何将目标="_blank"放入pug中

javascript - 无法在ajax的帮助下使用选择选项更新数量

java - 将一维数组转换为二维数组

C++ 在编译时知道给定类型的对象数

javascript - React - 2路绑定(bind)文本输入,存储和显示的格式不同

reactjs - Recharts 设置显示数字的 Y 轴值基数