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
Related
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.
I want to display a list of items, now sometimes these items' title will just be a plain string, and sometimes it might be a value returned by a function.
How can I make both events work using eval() ?
Here is an example code:
var a1 = "formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')"
var a2 = "#america"
var result1 = eval(a1) // works well!
var result2 = eval(a2) // doesn't work, need to use eval('a2') but then first one doesn't work
Only thing I can think of is when creating the string for example "#america" have it saved like "'#america'" instead, but I would rather avoid it
[edit]
Eventually I will have something like this:
arr.push("formatDate('" + startTime + "') + ' - ' + formatDate('" + endTime + "')");
arr.push("#america");
for(var i = 0; i < arr.length; i++) {
var ev = eval(arr[i]);
console.log(ev);
}
What I would suggest is wrapping the eval in a try catch block, if the eval succeeds then return the value otherwise return the value originally passed to function. There are many cases where eval can fail as it is simply trying to parse the string as valid JavaScript so any invalid JS not just a simple string can cause it to fail so its better to be safe and catch any error that comes out of it.
var evaluate = function(value) {
try {
return eval(value);
}
catch(err)
{
return value;
}
}
var ev = eval(a2) would be equivalent to var ev = eval('#america') which doesn't make any real sense.
When you say eval('a2') works, I assume that ev = '#america' is the desired outcome. The 'a2' expression is evaluated as simply accessing the value of the variable of that name.
You're basically just having a series of strings that may be valid javascript code, or may not, and there's no way to tell which is which. In that case, the best you can do is something like
try {
ev = eval(arr[i]);
} catch(ex) {
ev = arr[i];
}
... which obviously looks terrible. Can you control the content of the entries in arr?
arr.push(function() {
return formatDate(startTime) - formatDate(endTime);
});
arr.push("#america");
In that case, you could check for the type of each entry, and act on it accordingly:
for(var i = 0; i < arr.length; i++) {
var ev = typeof arr[i] == 'function' ? arr[i]() : arr[i];
console.log(ev);
}
this is that i should do:
var a1 = function(){
return formatDate(startTime) + formatDate(endTime)
}
var a2 = "#america"
var result1 = a1();
var result2 = a2;
Yo can check with typeof(a1) if the var is a function or an object or anyting else.
if(typeof(a1)=='function'){
result = a1();
}else{
result=a1;
}
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
I suspect I am making a mistake in a basic JavaScript syntax.
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
var my_array+count = "This is a variable number "+count+".";
document.write(my_array+count);
}
I want the loop to create series of variables that should be called my_array0, my_array1, my_array2, and so on. The code above is how I tried to do that, but it doesn't work. What's the correct way of naming the variable inside the loop?
EDIT: I know I could use my_array[count], but that's not what I'm looking for. What I need is to be able to name a variable inside the loop, using the index as part of the name of the variable.
If you want to set the elements of an array, use the [] syntax:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
document.write( my_array[count] );
}
Furthermore, when specifying just an element of an array and not the array itself, drop the var in front of it!
This pattern is questionable, and the array seems unnecessary; however, here is one way to do it:
var my_array = new Array(10);
for (var count = 0; count < my_array.length; count++) {
window['my_array' + count] = "This is a variable number " + count + ".";
document.write(window['my_array' + count]);
}
What's the correct way of naming the variable inside the loop? You don't.
If you just want a variable to hold that particular value, just use an ordinary variable. If you want lots of different values, stick it inside an array or object. But that's redundant here since you already have an array, so I'm really not sure what you're trying to achieve.
And if none of the previous answers suits you, you can always use eval()
var varName = 'my_array'
for (var count=0; count<my_array.length; count++) {
eval(varName+count +" = This is a variable number "+count+".");
}
Edit: #Noah Freitas provides a better answer, without using eval().
You're redefining my_array inside the loop, and not accessing the variable correctly either. Try:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
console.log(my_array[count]);
}
JS Fiddle
You can't execute on the left-hand side of the assignment operator (=), you can only assign. Execution, in javascript, takes place on the right hand side.
var my_array = new Array(10);
var var_hashmap = {}; // create a new object to hold our variables.
for (var count = 0; count < my_array.length; count++) {
var key = "my_array" + count;
var value = "This is a variable number " + count + ".";
var_hashmap[key] = value;
document.write(var_hashmap[key]);
};
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++)
{
eval("var my_array" + count + " = 'This is a variable number'+count+' and the variable name is my_array'+count");
}
alert(my_array0);
alert(my_array1);
alert(my_array2);
alert(my_array3);
alert(my_array4);
alert(my_array5);
alert(my_array6);
alert(my_array7);
alert(my_array8);
alert(my_array9);
http://jsfiddle.net/pe97W/4/
You should use an array.
var myarray = new Array();
myarray[0] = "1";
myarray[1] = "2";
myarray[2] = "3";
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.