2

I want some jquery variables to be created dynamically. In my code I am having a loop, and with the loop values I want to create some variables. Here is my sample code.

array=["student","parent","employee"]

$.each(user_types, function( index, value ){
  var value+"_type" // this is the type of variable i want to build.
})

I have found about eval function. That code goes like this.

var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");

alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.

Is there any alternate ways as I have read the eval function is not prefered while coding .js files.

2
  • 1
    duplicate stackoverflow.com/questions/5187530/… Commented Nov 14, 2013 at 11:50
  • 1
    var pres = {}; var type = "foo"; pres[type] = "something"; - "dynamic keys" Commented Nov 14, 2013 at 11:51

3 Answers 3

13

Any time you find yourself using a variable in the name of a variable, you probably want to use an object literal. Create the object with curly braces {}, and then set the object property key using square bracket notation:

var user_types = ["student","parent","employee"];
var types = {};

$.each(user_types, function( index, value ){
  types[value] = 'The value of dynamic variable, val';
});

JSFiddle

Note: You haven't tagged it, but I assume because you've used each() that you are using jQuery, please correct me if I'm wrong.

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

2 Comments

Thanks, I think this would be better and elegant solution than using the eval as this will not pollute my global scope. And I am using jquery over here. Let me try and will post you back.
this is most helpful for me
6

First of all i must say that i can't think of any reason why you want to do this.

If you really need to have those variables, in global scope, you can do the following:

var array=["student","parent","employee"]

array.forEach(function(value){
  window[value+"_type"] = 'My value ' + value;
});

console.log(student_type);
console.log(parent_type);
console.log(employee_type);

If you don't want the variables in global scope, i'm afraid i don't know an elegant solution.

I used array.forEach instead of your jQuery loop because the problem is not related to jQuery at all and because i don't think you said enough of your logic to make a coherent example.

EDIT: I should make it clear that while the 'variables' created behave mostly like other variables in global scope, they are NOT variables. Here is how they differ:

// Difference 1: hoisting
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
var x = 5;
window[y] = 5;
console.log(x); // 5
console.log(y); // 5
// Difference 2: [[Configurable]] 
delete x;
delete y;
console.log(x); // 5
console.log(y); // ReferenceError: y is not defined

2 Comments

Thanks for the enlightment. I have made up my mind for using eval funtion. I wanted to created some custom names that will be dynamically generated and can store some values. I can achieve by the way that oGeez has mentioned below. I tried it with windows, works fine. But I found the other way was better to deal with my case.
@DeepakA I'm glad. As i said in the first line, i don't think there is ever a reason to do what i wrote in this post :). The knowledge doesn't hurt though.
0

If you want to add an intermediate variable inside the string, you can do it as follows:

var itemSelect: number = 1;
$(`#tab${this.itemSelect}-tab`).tab('show');
/* Result -> $(`#tab1-tab`).tab('show');  */

/* HTML */
<a id="tb1-tab"> </a>

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.