Is there a way to loop this? - javascript

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]);
}

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.

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.

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał

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

For loop to convert series of variables

I'm trying to create a for loop that does the exact same thing as this code (quests is an array):
Quest0.text = quests[0]
Quest1.text = quests[1]
Quest2.text = quests[2]
Quest3.text = quests[3]
Quest4.text = quests[4]
Quest5.text = quests[5]
Quest6.text = quests[6]
Quest7.text = quests[7]
Quest8.text = quests[8]
Quest9.text = quests[9]
Quest10.text = quests[10]
Quest11.text = quests[11]
Quest12.text = quests[12]
Quest13.text = quests[13]
Quest14.text = quests[14]
Quest15.text = quests[15]
So far all I've got is this (activeQuests is the length of the array quests):
var q = 0;
for (q=0; q <= activeQuests; q++) {
Quest0.text = quests[q]
}
But I don't know how to get it to do the rest.
You could use eval but you probably shouldn't. You should probably rethink your approach if you have such obviously array-like data that you are manipulating manually element by element.
Check out this blog post from Marco van Hylckama Vlieg: "Variable Variables in Javascript". Relevant snippet:
...using the fact that all global variables are held in the window
array.
var i=1;
window['name' + i] = 'Marco';
document.write('got ' + name1);
There we go! Nice, clean and no eval() necessary."
We'd need to know more to give you exact code, but in order to address a variable by string, it needs to be a property of an object. For example
window.example = 'hello world';
alert(window['example']);
So it really depends on what your QuestN variables are. Are they id's of <input> elements? Are they global variables? Are they defined in local scope with the var keyword?
If you can change how Quest.. are defined then define them as an array so you can do:
Quest[q].text = quests[q];
if you can't then temporarily create an array of Quest.. objects:
var QUESTS = [];
QUESTS[0] = Quest0;
QUESTS[1] = Quest1;
QUESTS[2] = Quest2;
QUESTS[3] = Quest3;
QUESTS[4] = Quest4;
QUESTS[5] = Quest5;
QUESTS[6] = Quest6;
QUESTS[7] = Quest7;
QUESTS[8] = Quest8;
QUESTS[9] = Quest9;
QUESTS[10] = Quest10;
QUESTS[11] = Quest11;
QUESTS[12] = Quest12;
QUESTS[13] = Quest13;
QUESTS[14] = Quest14;
QUESTS[15] = Quest15;
Then you can do:
for (var q=0; q<=activeQuests; q++) {
QUESTS[q].text = quests[q]
}
Obviously this is an uglier solution but much better than eval IMHO.
I think you are better off keeping the "quests" array than defining a different variable to each index.
However if you want to loop try eval("Quest" + q + ".text = quests[q]") in the loop.

Categories

Resources