I’m doing some simple javascript learning at the moment and I’m stuck on how to solve this problem. (the basic form comes from Code Academy). The task is to create 3 rabbit objects, each with a different adjective as an attribute. Then, print describeMyself() for each rabbit.
Instead of repeating myself 3 times, I’d like to find a way to solve the problem with a for loop to make it more streamlined/challenging for myself. Here’s what I tried:
function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}
var rabbit1 = new Rabbit(fluffy);
var rabbit2 = new Rabbit(happy);
var rabbit3 = new Rabbit(sleepy);
for (i=1; i<=3; i++){
("rabbit"+i).describeMyself();
}
Obviously, the ("rabbit"+i).describeMyself() is wrong. I want the loop to create “rabbit1”, “rabbit2” and “rabbit3”. What’s the proper syntax here?
First of all, the parameters you are passing will result in undefined. If you want to pass strings, then use quotes to mark them as such. Second of all, creating new instances in a for loop means you will have to store them somewhere else, like in an array for instance.
For future reference, don’t forget to mark strings with single quotes or double quotes for HTML strings. The above should be: