JVG
JVG

Reputation: 21150

Javascript for loop with variable

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?

Upvotes: 0

Views: 584

Answers (8)

Deepika Sahu
Deepika Sahu

Reputation: 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.

Upvotes: -1

Lloyd
Lloyd

Reputation: 29668

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();
}

Upvotes: 0

Lucian Enache
Lucian Enache

Reputation: 2520

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();
}

Upvotes: 1

flavian
flavian

Reputation: 28511

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

Upvotes: 3

Constantine
Constantine

Reputation: 699

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();
}

Upvotes: 0

Stuart
Stuart

Reputation: 9858

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();
}

Upvotes: 0

WTK
WTK

Reputation: 16961

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

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72837

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)

Upvotes: 1

Related Questions