I am newbie with javascript and meet a problem like this.
For example . there is a variable with a list like this
{
name: 'x',
attack: 50,
speed: 100,
hitpoint: 100,
},
{
name: 'y',
attack: 150,
speed: 80,
hitpoint: 180,
}
Find an variable with an attack = 150 and return it in the function "findAMonsterByAttack" If there is no matching variable in the list of variable, the "findAMonsterByAttack" function returns null.
Here is my code :
function findAMonsterByAttack(monsters) {
var monsters = [
{
name: 'x',
attack: 50,
speed: 100,
hitpoint: 100,
},
{
name: 'y',
attack: 150,
speed: 80,
hitpoint: 180,
},
// ...
];
var isfree = monsters.every(function(course, index) {
return course.attack ===150;
});
My idea is using the code every to check course and index, then return if the attach = 150. But I failed. Could you please help me with this case ? Thank you very much for your time.
CodePudding user response:
If monsters
is an array, you can use array.filter to return another array with of only the monsters
with matching criteria
eg attack === 150
.
Note that there could be multiple matches, so this would return an array with all of the monsters
that match, (or an empty array if no monsters
match).
const monsters = [{
name: 'x',
attack: 50,
speed: 100,
hitpoint: 100,
},
{
name: 'y',
attack: 150,
speed: 80,
hitpoint: 180,
},
{
name: 'z',
attack: 150,
speed: 90,
hitpoint: 150,
}
]
const a150 = monsters.filter(m => m.attack === 150)
console.log(a150)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If you only care about one monster
, you could also use array.find. But this would return the first monster
found and undefined
if no matches are found.
const monsters = [{
name: 'x',
attack: 50,
speed: 100,
hitpoint: 100,
},
{
name: 'y',
attack: 150,
speed: 80,
hitpoint: 180,
},
{
name: 'z',
attack: 150,
speed: 90,
hitpoint: 150,
}
]
const a150 = monsters.find(m => m.attack === 150)
console.log(a150)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Note: array.every tests whether all monsters
meet the criteria and returns a Boolean
value. In your example this will return false
because all monsters
do not have an attack value of 150.
CodePudding user response:
Is this what you want?
function findAMonsterByAttack() {
var monsters = [
{
name: 'x',
attack: 50,
speed: 100,
hitpoint: 100,
},
{
name: 'y',
attack: 150,
speed: 80,
hitpoint: 180,
}
// ...
];
for ( m of monsters ) {
if ( m.attack == 150 )
return m
}
return "Monster with attack 150 not found"
}
console.log(findAMonsterByAttack())