Using a variable increment to create new variables in Javascript - 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.

Related

How to keep changing the the reference name by loop which is pointing to the object in javascript? [duplicate]

I'm working on an ajax google maps script and I need to create dynamic variable names in a for loop.
for (var i = 0; i < coords.length; ++i) {
var marker+i = "some stuff";
}
What I want to get is: marker0, marker1, marker2 and so on.
and I guess there is something wrong with marker+i
Firebug gives me this: missing ; before statement
Use an array for this.
var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}
I agree it is generally preferable to use an Array for this.
However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this – which always refers to the current scope.
for (var i = 0; i < coords.length; ++i) {
    this["marker"+i] = "some stuff";
}
You can later retrieve the stored values (if you are within the same scope as when they were set):
var foo = this.marker0;
console.log(foo); // "some stuff"
This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.
Try this
window['marker'+i] = "some stuff";
In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval() is even another option.
v0 = "Variable Naught";
v1 = "Variable One";
for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
dyV = eval(`v${i}`);
console.log(`v${i}`); /* => v0; v1; */
console.log(dyV); /* => Variable Naught; Variable One; */
}
When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval() to get the value is kind of lame when you're used to getting it automatically.
_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}] //Array of Object(s)
for (i = 0; i < 3; i++)
{
console.log(`_${i}`); /* var
* => _0 _1 _2 */
console.log(`"_${i}"`); /* var name in string
* => "_0" "_1" "_2" */
console.log(`_${i}` + `_${i}`); /* concat var with var
* => _0_0 _1_1 _2_2 */
console.log(eval(`_${i}`)); /* eval(var)
* => My first variable
Object {key_0: "value_0"}
[Object] */
}
You can use eval() method to declare dynamic variables. But better to use an Array.
for (var i = 0; i < coords.length; ++i) {
var str ="marker"+ i+" = undefined";
eval(str);
}
In this dynamicVar, I am creating dynamic variable "ele[i]" in which I will put value/elements of "arr" according to index. ele is blank at initial stage, so we will copy the elements of "arr" in array "ele".
function dynamicVar(){
var arr = ['a','b','c'];
var ele = [];
for (var i = 0; i < arr.length; ++i) {
ele[i] = arr[i];
] console.log(ele[i]);
}
}
dynamicVar();
var marker = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);
var marker+i = "some stuff";
coudl be interpreted like this:
create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible.
What firebug is saying is this:
var marker; i = 'some stuff';
this is what firebug expects a comma after marker and before i;
var is a statement and don't (apparently) accepts expressions.
Not so good an explanation but i hope it helps.

jQuery .each function not persisting global variable

I have a function whereby I wish to run a .each loop and return the running total of the values
At the end of my .each function, the amountSold variable is 0 and during the .each loop, it is shown as undefined. What am I doing wrong?
function processChange(currentTarget) {
var amountSold = 0; //VARIABLE DECLARED
//limit these operations to the currentlySelected tab
var availableFundContainer = $(currentTarget).closest(".available-content").parent();
var fundBeingSold = $(availableFundContainer.children(0)).attr('data-investment-code');
availableFundContainer.find('.available-handler').each(function (index, val) {
var origVal = $(this).attr('data-original-value');
var currentSliderVal = $(this).next('.available-content').find('.slider').slider("value");
var amountSold = amountSold + (origVal - currentSliderVal); //PROBLEM LINE!!!!!
....}
You're creating a locally scoped variable, also called amountSold, inside the each callback function.
Replace
var amountSold = amountSold + (origVal - currentSliderVal); //PROBLEM LINE!!!!!
with
amountSold += (origVal - currentSliderVal); //PROBLEM LINE!!!!!
You are confused with how the function scope works in JS. Consider the following example:
var someArray = [0,1,2,3,4,5];
var a = 0;
var b = 0;
someArray.forEach(function(item) {
a = a + item;
var b = b + item;
console.log("loop", a, b);
});
console.log("final", a, b);
Run the snippet, and you will see that within the loop, the variable b starts out as undefined. This is so, because the function passed to the forEach method creates a new scope, and any variables declared with the var statement, will override any variables that exist in the parent scope. In this case, it means that b ends up being NaN. On the other hand, a keeps its previous value and increments as expected.
The final console log demonstrates, that the value of b in the global scope was not changed by the statements executed in the loop.
This feature of JS allows a user to create a functions that do not have side effects on the global scope.
And to answer your question, you are using the var statement:
var amountSold = amountSold + (origVal - currentSliderVal);
when you should be using a simple assignment
amountSold = amountSold + (origVal - currentSliderVal);
Make the variable global using
window.amountSold = 0
Inside the loop just call it the same way
window.amountSold += (origVal - currentSliderVal);

Is there a way to loop this?

Is there a way to loop a declaration of a variable? just a loop to help me declare the variables so i dont have to do the monotonous work of change the numbers of the variable
var height1 = document.getElementById('height1').value;
var height2 = document.getElementById('height2').value;
var height3 = document.getElementById('height3').value;
var height4 = document.getElementById('height4').value;
var height5 = document.getElementById('height5').value;
var height6 = document.getElementById('height6').value;
var height7 = document.getElementById('height7').value;
var height8 = document.getElementById('height8').value;
var height9 = document.getElementById('height9').value;
var height10 = document.getElementById('height10').value;
var height11 = document.getElementById('height11').value;
var height12 = document.getElementById('height12').value;
var height13 = document.getElementById('height13').value;
var height14 = document.getElementById('height14').value;
var height15 = document.getElementById('height15').value;
var height16 = document.getElementById('height16').value;
This is not a right way of coding that, Just do like,
var heights = [];
Array.from(document.querySelectorAll("input[id^=height]")).forEach(function(itm){
heights.push(itm.value);
});
And now you can iterate the array heights to manipulate the values as per your requirement.
The logic behind the code is, querySelectorAll("input[id^=height]") will select the input elements that has id starts with the text height. Since the return value of querySelectorAll is a nodelist, we have to convert it as an array before using array functions over it. So we are using Array.from(nodelist). That will yield an array for us. After that we are iterating over the returned array by using forEach and pushing all element's value into the array heights.
This is almost always an indication that you want an array. Something like this:
var heights = [];
for (var i = 1; i <= 16; i++) {
heights.push(document.getElementById('height' + i).value);
}
Then you can reference a value from the array with something like:
heights[1]
Though technically since in JavaScript your window-level variables are indexable properties of the window object, you can essentially do the same thing with variable names themselves:
for (var i = 1; i <= 16; i++) {
window['height' + i] = document.getElementById('height' + i).value;
}
Then you can still use your original variables:
height1
Though in the interest of keeping things outside of window/global scope, maintaining the array seems a bit cleaner (and semantically more sensible).
This seems to be a good use case for an object:
var heights = {};
for (var i = 1; i <= 16; i++) {
heights[i] = document.getElementById('height' + i).value;
}
Maybe its time to introduce function:
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
function getHeight(id) {
return document.getElementById(id).value;
}
Call with the wanted id and use it like a variable.
getHeight('height1')
Normally you would put them in an array.
var heights = []
for (i = 1; i < 17; i++) {
heights[i] = document.getElementById('height' + i).value;;
}
Beware this will give you a hole at the start of the array ie heights[0] has nothing in it. If you use this to iterate it won't matter...
for (var i in heights) {
alert(heights[i]);
}

Variable name within a loop

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";

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

Categories

Resources