Javascript 对象数组上的拼接函数

Javascript 对象数组上的拼接函数,javascript,arrays,reactjs,object,ecmascript-6,Javascript,Arrays,Reactjs,Object,Ecmascript 6,我正在做一个react/javascript练习,在理解splice()在其中的用法时遇到了一些问题。 我有8张牌,我需要随机分配4张牌给2个玩家。现在一切正常,但我不理解让randPokemon=hand2.splice(randIndex,1)[0]结尾的[0]行 以下是完整的代码: import React, { Component } from "react"; import Pokedex from "./Pokedex"; class Pokegame extends Compon

我正在做一个react/javascript练习,在理解
splice()
在其中的用法时遇到了一些问题。 我有8张牌,我需要随机分配4张牌给2个玩家。现在一切正常,但我不理解
让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;

import React,{Component}来自“React”;
从“/Pokedex”导入Pokedex;
类Pokegame扩展组件{
静态defaultProps={
口袋妖怪:[
{id:4,名字:“查尔曼德”,类型:“火”,经验:62},
{id:7,名字:“斯奎特尔”,类型:“水”,经验:63},
{id:11,名称:“Metapod”,类型:“bug”,经验:72},
{id:12,名字:“无黄油”,类型:“飞行”,经验:178},
{id:25,姓名:“皮卡丘”,类型:“电动”,经验:112},
{id:39,名字:“Jigglypuff”,类型:“normal”,经验:95},
{id:94,名字:“根格”,类型:“毒药”,经验:225},
{id:133,姓名:“Eevee”,类型:“normal”,经验:65}
]
};
render(){
让hand1=[];
let hand2=[…this.props.pokemon];
while(hand1.length
我理解(如果我错了,请纠正我)
splice()
函数可以接受两个或多个参数:第一个是告诉添加/删除项的位置的索引,第二个是要添加/删除项的数量,下一个参数是我们要添加的项(但我不在这里使用它,因为我只想删除所选项目并将其添加到第一手中)


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

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

如果查看,您将看到它实际上返回一个由操作删除的项目数组

因此,在本例中,它将从随机索引处的
hand2
数组中删除一个口袋妖怪,并返回一个包含一个项目的数组


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

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

let [randPokemon] = hand2.splice(randIndex, 1);
根据
splice()的返回值,
是由从数组中删除的元素组成的数组

返回值 包含已删除元素的数组。如果仅删除一个元素,则返回一个元素的数组。如果未删除任何元素,则返回空数组


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

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

这是因为拼接返回一个数组,您需要第一项。这就是[0]的原因。@JackBashford我可以问您编辑标记的原因吗?非常感谢您的回答!