Apply for loop with variable - javascript

I am trying to condense my code because I have a lot of repetitive coding happening. I will need to apply this same example many times over. I want to create a for loop but my variable needs to increase as well. Right now I have my variable increasing but I am unable to implement my cell data into the variable. I think I am double assigning var h. I can't figure out how to get around this. Thank you for your help.
For Loop
for (var j = 2; j<15; j++){eval("var polebrea" +j);
var h = ("polebrea" +j)
}
h = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
Code Attempting To Implement
polebrea2 = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
polebrea3 = document.getElementById("part1Table").rows[10].cells[3].innerHTML;
polebrea4 = document.getElementById("part1Table").rows[10].cells[4].innerHTML;
polebrea5 = document.getElementById("part1Table").rows[10].cells[5].innerHTML;
(cont. to 15)
Inserting Variable
<script>document.write(polebrea2)</script>

Ignoring design dogma....use the string index form of property access to set your variables:
// window is a bad place for this....you should probably put it on another object e.g. var polbreas = {};
for (var i = 2; i<15; i++){
window["polbrea"+i] = document.getElementById("part1Table").rows[10].cells[i].innerHTML;
}

While not necessarily good practice to do what you are doing, you could try this:
var createVariable = function( index ){
var variableName = "polebrea" + index;
var objName = document.getElementById("part1Table").rows[10].cells[index].innerHTML;
return (variableName + " = " + objName + ";");
};
for (var j = 2; j<15; j++){
var objToWrite = createVariable(j);
console.log( objToWrite );
}

Related

Setting the value in a for loop in Javascript

I have a for loop that i need to increase the value of on each iteration, and a few examples of what I have tried so far. I need to increase the value of tp on each loop through:
for (var t = 9; t < 20; t++) {
//Tried the below:
var timePeriod = report_data[i] + '.tp' + t.toString();
venues[i].scan_times[t] = timePeriod;
//and:
venues[i].scan_times[t] = report_data[i].tp + t;
}
The manual way of doing it, which I am trying to use the for loop to accomplish:
venues[i].scan_times['9'] = report_data[i].tp9;
venues[i].scan_times['10'] = report_data[i].tp10;
....
venues[i].scan_times['19'] = report_data[i].tp19;
venues[i].scan_times['20'] = report_data[i].tp20;
In javascript you can always access attributes in two ways: with bracket notation and dot notation
var myObj = {};
// those 2 lines are equivalent
myObj.a = 1;
myObj['a'] = 1
If you want to dynamically access some attributes you can use whatever you want inside the brackets.
// those 2 lines are equivalent
myObj['a' + 4] = 1;
myObj.a4 = 1;
In your case you can write
for (var t = 9; t < 20; t++) {
venues[i].scan_times[t] = report_data[i]['tp' + t];
}

Syntax to build object properties in loop - javascript

I would like to loop through a list of objects and display one property on a graph on the page but I can't seem to get the right syntax to get this data in a loop.
Without the loop this gives an idea of what I want to do:
document.getElementById("v1").innerHTML = zone1.sensor;
document.getElementById("v2").innerHTML = zone2.sensor;
document.getElementById("v3").innerHTML = zone3.sensor;
I can't figure out how to loop through the objects, something like this:
for(i = 1; i < 7; i++) {
document.getElementById("v" + i).innerHTML = ("zone" + i + ".sensor");
}
While that can be done with eval() or new Function (), that's just plain wrong. Put your values in an array and access them by index. If you absolutely have to use independent variables, do:
var arr = [zone1, zone2, zone3];
and then use
arr[i].sensor
I would go this way to avoid the use of eval:
var zone1 = new Object;
var zone2 = new Object;
var zone3 = new Object;
zone1.sensor = "sensor1";
zone2.sensor = "sensor2";
zone3.sensor = "sensor3";
var zones = [zone1, zone2, zone3];
for( var i = 1; i < 4; i++) {
document.getElementById("v" + i).innerHTML = zones[i - 1]["sensor"];
}
<div id="v1"></div>
<div id="v2"></div>
<div id="v3"></div>
Hope it helps!

javascript how to pass each element in an array to different var

I am new to javascript and recently have a problem to passing elements from array to var.
For example, I have an array like var anArray = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]], and I have 3 different var a , b and c.
after some loop codes,
what I would like to see is:
while a=a1, b should be b1 and c=c1
while a=a2, b=b2 and c=c2
while a=a3, b=b3, c=c3
also pls consider that what if I have array like:
[[a1,a2,a3],[b1,b2,b3]] which will result a=a1 while b=b1, a=a2 while b=b2 etc.
or [[a1,a2],[b1,b2],[c1,c2]] which will result a=a1 while b=b1 and c=c1, a=a2 while b=b2 and c=c2
If my question is still not clear enough, please comments it and I will update it.
I really appreciate all the comments and the code that you have made! Many thanks!
You have a bunch of pieces backwards and in the wrong place:
var anArray = [[1,2],[1,2]];
for(var i=0;i <= anArray.length - 1;i++)
{
for(var j=0;j<anArray[i].length;j++){
var a = anArray[i][j];
var b = anArray[i + 1][j];
alert("a: "+a+" and b: "+b);
}
}
Edit: adjusted after you changed your entire question.
Let say that we have have an array like thisvar anArray = [[1,2,3],[4,5,6]];
and if you want to alert this a=14;b=25;c=36; then you can use this code
var anArray = [[1,2,3],[4,5,6]];
for ( i = 0; i < anArray.length; i++ ) {
var l = anArray[i];
for ( m = 0; m < l.length; m++ ){
this["a"+i+m.toString()] = l[m];
}
}
alert("a = "+ a00 + a10.toString());
alert("b = "+ a01 + a11.toString());
alert("c = "+ a02 + a12.toString());
Where a00=1; a01=2; a02=3; these are the elements of the first array.(the middle nr. tells the array so for the first array we use 0).
Then we have a10=4; a11=5; a12=6; these are the elements of the 2nd array.(the middle nr. tells the array so for the second array we use 1).
All you have to do is just replace this arrayvar anArray = [[1,2,3],[4,5,6]] with yours and let
javascript do its job.
After you clarified your question I got a general idea of what you want. I think this is what you want to achieve. The example is dynamic so that as long as the length of item in the array is equal.
var anArray = [[1,2,3],[4,5,6],[7,8,9]];
for(var j=0;j<anArray[0].length;j++){
var values = [];
for(var i=0;i<anArray.length;i++) {
values[i] = anArray[i][j];
}
//Do what you want with the values below. I chose to show them in a alert message
var text = '';
for(var i=0;i<anArray.length;i++) {
if(text.length>0){ text += ',' };
text += values[i];
}
window.alert('Values: ' + text);
}
PS: There were not 1 but a few things wrong with your code.

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

Programmatically setting the name of a variable

Is there a shortcut for writing the following 100 assignments?
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
...
variable_100 = 100;
I have tried
for(var i = 1; i <= 100; i++) {
variable_ + i = i;
}
but I get the error message "Invalid left-hand side in assignment". Any ideas?
Here are a few methods:
Method 1: use eval
Here is the most direct method:
for(var i = 1; i <= 100; i++) {
eval("var variable_" + i + " = " + i);
}
variable_1; // => 1
Disclaimer for the above method: I don't think this problem is a good candidate for using eval. If you do use eval, you should never allow user input to go into what you are evaling, or you could open your site to security risks. That mistake is the main reason people say eval is evil.
Method 2: use dynamically generated object properties
This is a much, much better way:
// If you want these variables to be global, then use `window` (if you're
// in a browser) instead of your own object.
var obj = {};
for(var i = 1; i <= 100; i++) {
obj["variable_" + i] = i;
}
obj.variable_1; // => 1
About the note in the comment about using window to create global variables: I would recommend against this, as it is a quick way to pollute your global scope and step on variables unwittingly.
Method 3: use an array
David suggested using an array. This is another great idea, and, depending on what you are trying to do, may be preferred:
var arr = [];
for(var i = 1; i <= 100; i++) {
arr.push(i);
}
arr[0]; // => 1
This will do it:
for(var i = 1; i <= 100; i++) {
eval("variable_" + i + " = " + i + ";");
}
eval is basically evil, but for such purpose it's OK to use it. (reference)
Live test case.
You are better off using an array
var variable = [];
for (var i=1; i <= 100; i++) {
variable[i] = i;
}
Later, you can access the values using variable[1], variable[2] etc.
If it is like that why not to define array of the objects
var a = new Array();
for(i=0;i<100;i+=)
a[i] = i;
Why not using an array instead like this?
<script language="javascript">
var arrayVar = new Array();
for (var i=0; i<100; i++) {
arrayVar["variable_" + i] = i;
}
</script>
Use an array:
var variable = [];
for(var i = 1; i <= 100; i++) {
variable[i] = i;
}
By way of analogy, you'd want to use an array instead of 100 variables for the same reason you'd want
<div class="variable"></div>
<div class="variable"></div>
<div class="variable"></div>
//and so on
instead of
<div id="variable_1"></div>
<div id="variable_2"></div>
<div id="variable_3"></div>
//and so on
<div id="variable_100"></div>
Invalid left-hand side in assignment
This error gets generated because variable_ + i is an expression. The interpreter thinks you are trying to add two variables instead of concatenating a variable name and a string. An expression cannot be on the left-hand side of an assignment operation.
for(var i = 1; i <= 100; i++) {
window["variable_" + i] = i;
}
alert( variable_50 );
alert( variable_34 );
Assuming you're on a browser you can do:
global[variable] = 'hello'
console.log(variable) -> hello

Categories

Resources