Setting the value in a for loop in Javascript - 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];
}

Related

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!

Apply for loop with variable

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

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.

How to make calculations in Javascript?

i = 3;
j = 2;
function domath(x) {
i = 4;
j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
The above JavaScript code does not return the expected results (as indicated by the comments in the code). Please correct the code for me anyone ?
As you're not using var , the variables i and j you're defining in the first lines are actually the same variable as you define in your domath() function...
try this :
i = 3;
j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
P.S : it could be a good idea to vary your variable name in order to make your code more readable
Declare your variables using var:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
It seems to be a really nasty way to do things.
I would personally do something like:
var v1;
var v2;
function math(x){ //do math here then return}
alert(math(1))
If you really have to use the same varible every where at least do it like:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
Also meaningful varibles names will keep you on a good track and using var and not global will also help you!
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
var x = domath(i) - j; // overwriting J will change your next expected result
alert(x); //expected result = 11
var k = domath(i) + j;
alert(k); //expected result = 15
The problem is you're overwriting global variables, i.e. screwing up your math:
j = domath(i) - j;
This expression is evaluated from left to right. The call to domath() will assign new values to i and j, so the effective code here would be this:
j = (i = 4) * 3 + 1 - 1;
So once this is done, j will be set to 12, which is indeed not 11. In addition, i will have a value of 4.
To use local variables within your function, you'll have to redeclare them, essentially hiding the global variables being outside this scope:
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
This time, the first assignment will be resolved to this, because domath() won't touch i and j assigned outside:
j = 4 * 3 + 1 - 2
Once this i done, j will be set to 11, just as expected.
To avoid such issues, it's good practice to always use var when defining new variables (which you'll have to do when wanting to write strict code anyway), and not to use such short, not-telling variable names. I'd consider limiting the use of one-character variable names to iterators and other things with very limited scope. Never for something being global.

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