我一直在尝试创建一个带有 4 个参数的函数,该函数允许我将对象推送到现有数组中。但是,我没有得到我想要的结果。例如,这是现有数组:
const firstGen = [
{name: 'Mewtwo', hp: 110, type: 'physic'},
{name: 'Charizard', hp: 135, type: 'flying'},
{name: 'Pikachu', hp: 85, type: 'electric'},
{name: 'Totodile', hp: 55, type: 'water'},
{name: 'Bayleef', hp: 80, type: 'grass'},
{name: 'Typlosion', hp: 125, type: 'fire'}
]
这是我创建的函数:
const addPokemon = (pokedex, pokemonName, pokemonHp, pokemonType) => {
pokedex.push({pokemonName,pokemonHp, pokemonType})
}
示例输入:
addPokemon(secondGen, 'Lucario', 85, 'fighting')
但输出是:
{ name: 'Mew', hp: 110, type: 'physic' },
{ name: 'Arcanine', hp: 135, type: 'Fire' },
{ name: 'Raikou', hp: 140, type: 'electric' },
{ name: 'Blastoise', hp: 120, type: 'water' },
{ name: 'Gardevoir', hp: 100, type: 'grass' },
{ name: 'Scorbunny', hp: 45, type: 'fire' },
{ pokemonName: 'Lucario', pokemonHp: 85, pokemonType: 'fighting' }
如您所见,我的函数中的参数也出现在输出中,而不是数组的属性名称中。先感谢您。
所以,这部分代码
pokedex.push({pokemonName,pokemonHp, pokemonType})
实际上是一个简写
pokedex.push({pokemonName: pokemonName,pokemonHp: pokemonHp, pokemonType: pokemonType})
当变量名称和属性具有相同名称时使用此表示法。在您的情况下,您需要通过执行以下操作手动指定属性:
pokedex.push({name: pokemonName, hp: pokemonHp, type: pokemonType})
或将参数更改为:
const addPokemon = (pokedex, name, hp, type) => {
pokedex.push({name, hp, type})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句