【发布时间】: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