JavaScript Dynamic Variable Names [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 days ago.
Ok so I want to create variables as a user clicks threw the code every click adds a new variable. I am currently using jquery and javascript I can't do it server side this must be done in the browser.
newCount = document.getElementById('hello').innerHTML;
$('.hello').click(function(){
//set count fast enumeration
newCount++;
var hello + newCount = '<p>Hello World</p>';
});
so I want the variables to be hello1, hello2, hello3, hello4, etc.

You can only do that with bracket notation, which means you have to attach the variables to something.
The global scope would be window, so that would be window['hello' + newCount], but polluting the global namespace with a bunch of random properties doesn't sound like a good idea, so using an object seems better
var vars = {};
var newCount = parseInt($('#hello').html(), 10);
$('.hello').click(function(){
newCount++;
vars['hello' + newCount] = '<p>Hello World</p>';
});
alert( vars['hello1'] );
FIDDLE

you can use window
var window['hello' + newCount ] = '<p>Hello World</p>';
likewise..
newCount = document.getElementById('hello').innerHTML;
$('.hello').click(function(){
//set count fast enumeration
newCount++;
var window['hello' + newCount ] = '<p>Hello World</p>';
alert(window['hello' + newCount ]);
});

In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
window object:
var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
for more inforamtion
How do i declare and use dynamic variables in javascript?

I would just use a simple array to store the variables. Then the object with index n would be variable n etc..

Most simple way
var types = {};
for(var i=1; i<=3; i++){
types["ashish"+i] = 'The value of dynamic variable, val';
}
console.log(types);
you can test it on
jsfiddle

var newCount = 0;
$('#btn').click(function(){
newCount++;
$('#hello').html('hello' + newCount);
});
jsfiddle

Related

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

Dynamically Select Variable [duplicate]

This question already has answers here:
Access value of JavaScript variable by name?
(7 answers)
Closed 5 years ago.
I have 2 variables like so
var variable_1 = "foo";
var variable_2 = "bar";
I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.
$("input:checked").each(function() {
$(div).append('variable_'+$(this).val());
}
So I'd concatenate the text 'variable_' with the value of each checkbox.
Thanks!
You can use eval to get any variable values dynamically.
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
$(div).append(eval('variable_'+$(this).val()));
}
Note: it's not the best solution because eval has some security issues as well.
Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.
This one is a ternary if:
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
var isChecked = $(this).is(':checked');
var append = (isChecked) ? variable_1 : variable_2;
$(div).append(append);
}
Alternatively you could use a switch statement for multiple values.
If the variables are globals then you can use
var y = window["variable_" + x];
to read or
window["variable_" + x] = y;
to write to them dynamically.
Better practice however is to use an object to store them instead of using separate variables...
var data = { variable_1: null,
variable_2: null };
...
y = data["variable_" + x];
Javascript can also use eval to access dynamically variables, amazingly enough even local variables
function foo(s) {
var x = 12;
return eval(s);
}
console.log(foo("x"));
and even more amazingly this allows the dynamic creation of new local variables...
var y = 42;
function foo(s) {
var x = 1;
eval(s);
return y; // may be global y or a local y defined by code in s
}
foo("x") // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).
Create object with properties and access that properties via obj['prop'] notation, see code below:
var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
$("input:checked").each(function() {
var dynamicVariableName = 'variable_' + $(this).val()
var dynamicVarValue = myObj[dynamicVariableName];
$(div).append(dynamicVar);
}
If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

how to eval a string within a string using javascript

this works in PHP:
$i = 4;
$fruit4 = 'apple';
$answer = $fruit{$i};
echo $answer; // apple
so i hoped this would work in javascript:
var i = 4;
var fruit4 = 'apple';
var answer = fruit{i};
print(answer);
but no luck! is there a way to do this using javascript?
NOTE: i realize this is more easily done with an array (var fruit[4] = 'apple') but that isn't an option this time due to pre-existing constraints.
thanks in advance!
JavaScript has a way of accessing properties via square bracket notation so that you can use strings and variables to get to them.
For example, if your fruit4 (From the code in your post) is in the global scope in the browser:
var answer = window['fruit' + i];
Javascript has an function called eval, so try to use it.
For example
var answer = eval("fruit"+ i);
eval('var answer = fruit' + i);

How do I declare and use dynamic variables in JavaScript?

Suppose I need to declare a JavaScript variable based on a counter, how do I do so?
var pageNumber = 1;
var "text"+pageNumber;
The above code does not work.
In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
window object:
var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
How would you then access said variable since you don't know its name? :) You're probably better off setting a parameter on an object, e.g.:
var obj = {};
obj['text' + pageNumber] = 1;
if you -really- want to do this:
eval('var text' + pageNumber + '=1');
I don't think you can do it sing JavaScript.I think you can use an array instead of this,
var textArray=new Array();
textArray[pageNumber]="something";
Assuming that the variable is in the global scope, you could do something like this:
var x = 1;
var x1 = "test"
console.log(window["x" + x]); //prints "test"
However, a better question might be why you want such behaviour.
You could also wrap your counter in an object:
var PageNumber = (function() {
var value = 0;
return {
getVal: function(){return value;},
incr: function(val){
value += val || 1;
this['text'+value]=true /*or some value*/;
return this;
}
};
})();
alert(PageNumber.incr().incr().text2); //=>true
alert(PageNumber['text'+PageNumber.getVal()]) /==> true
It can be done using this keyword in JS:
Eg:
var a = [1,2,3];
for(var i = 0; i < a.length; i++) {
this["var" + i] = i + 1;
}
then when you print:
var0 // 1
var1 // 2
var2 // 3
I recently needed something like this.
I have a list of variables like this:
var a = $('<div class="someHtml"></div>'),b = $('<div class="someHtml"></div>'),c = $('<div class="someHtml"></div>');
I needed to call them using another variable that held a string with the name of one of these variables like this:
var c = 'a'; // holds the name of the wanted content, but can also be 'b' or 'c'
$('someSelector').html(eval(c)) // this will just use the content of var c defined above
Just use eval to get the variable data.
I just did
I know a lot of the other answers work great, such as window["whatever"] = "x"; but I will still put my own answer here, just in case it helps.
My method is to use Object.assign:
let dict = {};
dict["test" + "x"] = "hello";
Object.assign(window, dict)
a little improvement over bungdito's answer, use the dynamic variable dynamically
var pageNumber = 1;
eval("var text" + pageNumber + "=123456;");
eval(`alert(text${pageNumber})`);
note: usage of eval is strongly discourgae

How to use contents of array as variables without using eval()?

I have a list of variables or variable names stored in an array. I want to use them in a loop, but I don't want to have to use eval(). How do I do this? If I store the values in an array with quotes, I have to use eval() on the right side of any equation to render the value. If I store just the variable name, I thought I'd be storing the actual variable, but it's not working right.
$(data.xml).find('Question').each(function(){
var answer_1 = $(this).find("Answers_1").text();
var answer_2 = $(this).find("Answers_2").text();
var answer_3 = $(this).find("Answers_3").text();
var answer_4 = $(this).find("Answers_4").text();
var theID = $(this).find("ID").text();
var theBody = $(this).find("Body").text();
var answerArray = new Array();
answerArray = [answer_1,answer_2,answer_3,answer_4,theID,theBody]
for(x=0;x<=5;x++) {
testme = answerArray[x];
alert("looking for = " + answerArray[x] + ", which is " + testme)
}
});
You can put the values themselves in an array:
var answers = [
$(this).find("Answers_1").text(),
$(this).find("Answers_2").text(),
$(this).find("Answers_3").text(),
$(this).find("Answers_4").text()
];
for(x=0;x<=5;x++) {
alert("looking for = " + x + ", which is " + answers[x])
}
EDIT: Or even
var answers = $(this)
.find("Answers_1, Answers_2, Answers_3, Answers_4")
.map(function() { return $(this).text(); })
.get();
If your answers share a common class, you can change the selector to $(this).find('.AnswerClass').
If you need variable names, you can use an associate array:
var thing = {
a: "Hello",
b: "World"
};
var name = 'a';
alert(thing[name]);
This would make it easier to get the array populated.
var answers = new Array();
$("Answers_1, Answers_2, Answers_3, Answers_4", this).text(function(index, currentText) {
answers[index] = currentText;
});
As others have mentioned, if you can put the variables in an array or an object, you will be able to access them more cleanly.
You can, however, access the variables through the window object:
var one = 1;
var two = 2;
var three = 3;
var varName = "one";
alert(window[varName]); // -> equivalent to: alert(one);
Of course, you can assign the varName variable any way like, including while looping through an array.

Categories

Resources