I'm trying to create a function that adds a new animal object to an already existing array of animals. The code seems to work fine except that it adds the new object 3 times. I'm guessing it must have something to do with the 3 conditions in my if statement. I'm not sure how else to write this to get it where it only adds the new element once.
var pig = {
species: 'pig',
name: 'bob',
noises: ['oink', 'snort', 'fart', 'squeal']
}
//i function
//o adds new animal to animals array
//c takes 2 parameters, must check for unique name, name property >0, species property >0
//signature of 'function add(animals, animal) {'
function add(animals, animal) {
for (var i = 0; i < animals.length; i++) {
if ((animal.name.length > 0) && (animal.species.length > 0) && (animal.name !== animals[i].name)) {
animals.push(animal);
}
}
}
// console.log(animals)
add(animals, pig)
Aucun commentaire:
Enregistrer un commentaire