0

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?

3
  • 1
    A good idea would be to use an array rabbits, i.e. var rabbits = new Array(new Rabbit(fluffy), new Rabbit(happy), new Rabbit(sleepy));. Commented Dec 6, 2012 at 10:57
  • 1
    by the way, you should use var i in your for loop to keep it a local variable. Commented Dec 6, 2012 at 10:58
  • Good pickup @IngoBürk, I learned this yesterday (I'm only 2 days into learning Javascript) and it slipped my mind. Commented Dec 6, 2012 at 11:03

8 Answers 8

3

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.

var rabbits = [];
var descriptions = ['fluffy', 'happy', 'white', 'sleepy', 'dreamy'];
for (var i = 0; i < 5; i++) {
    rabbits.push(new Rabbit(descriptions[i]));
}

//Now you have 5 rabbits stored in the rabbits array. Now here's how to make them //egocentric.
for (var i = 0, ii = rabbits.length; i < ii; i++) {
    rabbits[i].describeMyself();
}


var rabbit1 = new Rabbit(fluffy);
var rabbit2 = new Rabbit(happy);
var rabbit3 = new Rabbit(sleepy);

For future reference, don't forget to mark strings with single quotes or double quotes for HTML strings. The above should be:

var rabbit1 = new Rabbit('fluffy');
var rabbit2 = new Rabbit('happy');
var rabbit3 = new Rabbit('sleepy');
Sign up to request clarification or add additional context in comments.

1 Comment

Quick question. With rabbits.push(new Rabbit(descriptions[i]));, what is being put into the array? For example, for i=0, does the array now have Rabbits('fluffy') in the 0 position? or is it new Rabbit(descriptions[0])? I guess what I'm asking is whether push() pushes whatever is in the brackets, or whether it actually runs the code in there and outputs the result.
1

Since the rabbits global variables, they are properties of the window object, so you could use:

for (i=1; i<=3; i++){
    window["rabbit"+i].describeMyself();
}

However,

I'd recommend using the array examples that have been suggested, though, since this is kindof a bad practice. (But nice to know)

2 Comments

@alex23: Yea, I posted this more because it's some additional information, for those that want to learn more.
I appreciated it. I'm literally only on my second day of learning Javascript so this is all new for me/trying to get my head around as much as possible!
1

Consider this a hackish answer, but provided you're would do this in global context, you could avoid ussing array and refer to your variables on window obejct like this:

var rabbit1 = new Rabbit('fluffy');
var rabbit2 = new Rabbit('happy');
var rabbit3 = new Rabbit('sleepy');

for (i=1; i<=3; i++){
    window["rabbit"+i].describeMyself();
}

Not to mention even more hackish and evil approach with eval (just putting it out there for reference):

for (i=1; i<=3; i++){
    eval("rabbit"+i+".describeMyself()");
}

2 Comments

Too slow ;-) Also, where's my crucifix? I spot a eval!
It seems that 3 people gave the hackish and evil answer at the same time, and only 2 apologised for it!
1

consider using an array of variables then use the index to access them like this

function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}

  var rabbit=[];

  rabbit[0]= new Rabbit("fluffy");
  rabbit[1]= new Rabbit("happy");
  rabbit[2]= new Rabbit("sleepy");


for (i=0; i<3; i++){

    rabbit[i].describeMyself();
}

8 Comments

Can you elaborate a little on your creation of the rabbits? As I see it you're creating an array called "rabbit" which is empty, then putting Rabbit ("fluffy"), happy and sleepy into the array in position 1 2 and 3?
Well consider that you start with an empty array and you fill it up with rabbits as you stated in your question. You could do this in many different ways but as far as I'm concerned for your problem I find it good this way.
That wasn't a critique, I was asking whether my interpretation of your code was correct :) still learning here. rabbit[1] means "the array, rabbit, in position 1" right? (or should it be 0, because arrays start at 0?)
Yes, but the 0-th is not initialized, especially not as a rabbit. The above code is not good. It will go out of bounds on the last loop turn.
true story @IngoBürk now I've fixed it :)
|
0

Sometimes it's useful to get the object to add itself to an array automatically.

​var rabbits = [];
function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
    rabbits.push(this); // all new Rabbits get added to the array rabbits
}
new Rabbit('happy');
new Rabbit('sleepy');
new Rabbit('fluffy');

for (var i = 0; i < rabbits.length; i++) {
    rabbits[i].describeMyself();
}

Comments

0

You were close, try this:

var attributes = ["fluffy","happy", "sleepy"];

for (i=1; i<=3; i++){
    window["rabbit"+i] = new Rabbit(attributes[i]);
}

for (i=1; i<=3; i++){
    eval(("rabbit"+i)).describeMyself();
}

Comments

0

You can't refer to the variables directly, but you can put them in an array/object:

var rabbits = [];

rabbits[1] = new Rabbit('fluffy');
rabbits[2] = new Rabbit('happy');
rabbits[3] = new Rabbit('sleepy');

for (var i= 0; i < 3; i++){
    rabbits[i + 1].describeMyself();
}

3 Comments

Can you explain what you've done with rabbits[1] et al? What do the square brackets do in this case? Also, why have you put rabbits[i+1] when i=1 in the for loop? (so you'd be getting rabbits[2],[3] and [4] here no?)
@Stuart - Yes you are right. I'm always thinking 0 based loops :P
@Jascination - Basically I've put rabbits not a keyed array and i'm using the loop counter as the key.
-1

try out this as it works completely fine in order to bring out the perfect result & here is the code:

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"); 

rabbit1.describeMyself(); 
rabbit2.describeMyself(); 
rabbit3.describeMyself();   

The problem is every one stucks & forgets to type "this.adjective=adjective;" i.e the 3rd line of the code due to which u will c an error as some undefined objects...Try out the above code to get the perfect output...its correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.