2
var b = '1'; 

How can I create a variable name using the contents of variable b? I am doing this in a each loop, so b will change.

I am wanting the final product to be something like:

var trip1 = ''; 

How would I accomplish something like that?

var trip + b = ''; var trip.b = ''; 
2
  • 2
    If you're always modifying the name by adding a numeric qualifier, then perhaps what you really want is an Array. Commented Dec 8, 2012 at 14:40
  • @ATLChris : aggreeing to what Pointy said , use an array like var b0=array[0] , var b1=array[1] , ... and so on Commented Dec 8, 2012 at 14:42

4 Answers 4

3

No, but you can do it with properties of an object:

var obj = {}; obj.b = '1' obj['trip' + obj.b] = ''; // or var obj = {}; var b = '1' obj['trip' + b] = ''; 

In JavaScript, you can access properties in two ways:

  1. Using a dot and a literal property name, e.g. obj.trip1.

  2. Using brackets and a string property name, e.g. obj['trip1'].

In the latter case, the string doesn't have to be a string literal, it can be the result of any expression, hence the examples above.

Sign up to request clarification or add additional context in comments.

Comments

1

I am doing this in a each loop

Since you are iterating over them, the best way to do this is to use an array.

var trip = [1,2,3,4,5]; for (var i = 0; i < trip.length; i++){ alert(trip[i]); } 

To address your question, you could store your values as properties of an object:

var obj = {}; var b = '1'; obj['trip' + b] = ""; 

If you are doing this in the global scope, you could also add the variable as a property of the global object:

var b = '1'; window['trip' + b] = ""; trip1; // == "" 

Comments

0

you can access global variables via the window object, using a dynmamic key like this:

var b = '1'; trip1 = 'hello'; console.log(window['trip'+b]); 

Comments

0

It sounds like you are looking for the eval() method.

var b = '1'; (eval('var trip'+b+' = 3')); // Is the same as writing var trip1 = 3; console.log(trip1); //Output of variable trip1 is 3 

Although, do a quick google search for why eval(); is bad before you employ this technique.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.