Marco
Marco

Reputation: 61

how to mix variables and loop indexes in javascript?

I got ten javascript variables named street1, street2, street3 ... street10.

I have to do a loop by putting into these variables. so I did:

var data;
for (var i=1;i<=10;i++)
{
data = data + 'this is street '+street+i+'\n';
}   

console log prints "street" does not exist...which is right because my variable is named street1. there's a way I can "mix" variables and index?

Upvotes: 0

Views: 64

Answers (4)

Nerixel
Nerixel

Reputation: 427

The generally accepted way to do this is using arrays. Your code would look something like this:

var streets = ["Park street", "First street", "Pine street", "Rainbow road", "Yellow brick road", "View street", "Ninth street", "Cedar street", "Lake court", "Hill street"];

for(var i = 0; i < streets.length; i++) {
    data += "this is street " + streets[i] + "\n";
}

The key improvement is that it will auto-adjust to however many streets are in the array due to the i < streets.length part of the for loop.

You could do it with eval(), but besides it being inefficient and more trouble than it's worth, that can be dangerous.

Upvotes: 1

Ian
Ian

Reputation: 34549

It would make more sense to store this item in an array:

var items = ["a", "b", "c"];
for (var i=0;i<3;i++)
{
   Console.log(items[i]);
}

Alternatively you can use square bracket notation. Accessing Street1 will depend on where it lives, assuming you've not scoped anything the following will get you the value, depending on where street1 is defined:

this['street' + i]
window['street' + i]

Upvotes: 3

Scimonster
Scimonster

Reputation: 33409

It is possible to use eval to do this, but it's slow, dangerous, and just all-around bad practice, so i'm not going to show you.

What you can do instead is to use an array.

var streets = ['street1','street2','etc.','street10'];

Then, you can loop through the array and get the values:

var data;
for (var i=0;i<10;i++)
{
data = data + 'this is street '+streets[i]+'\n';
}   

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78595

You really should use an array for this:

var street = [];
street.push("Fake St");
for(var i=0; i<street.length; i++) {
    data += "this is street: " + street[i] + "\n";
}

But you can achieve your original idea using bracket notation:

var data;
for (var i=1;i<=10;i++)
{
data = data + 'this is street '+ this["street"+i] +'\n';
}  

Upvotes: 3

Related Questions