Javascript - Dynamic variable - javascript

I am having problem to figure correct syntax to make those Javascript dynamic variable works:
I want to replace this code:
<code>
var res1 = res0.replace('[a1]', a1);
var res2 = res1.replace('[a2]', a2);
(...)
var res7 = res6.replace('[a7]', a7);
</code>
With something dynamic, like
<code>
for (var i = 1; i < 8; i++) {
**var str2 ="res" + i + " = res + i + .replace('[a + 'i']', window['a' + i])";**
eval(str2);
}
</code>
The ElementID is recovered from another Dynamic Variable, that works
<code>
for (var i = 1; i < 8; i++) {
var str ="a" + i + " = document.getElementById('a'+i).value";
eval(str);
}
</code>
General idea is simple.
Capture from a form, (input type text) and replace the strings called [a1], [a2], etc inside a textarea. Code works without dynamic variables.
Any idea is more than welcome.
Thank you

so don't use eval... bad practice, much bugs, little security, unexpected results...
it sounds like you just need an array.
(if you are using a for loop and eval - chances are you really want an array instead).
here is code that does not use eval()
reses = [] // of res0, res1 etc
for (let i = 1; i < 8; i++) {
reses[i].replace(`[a${i}]`, window[`a${i}`]);
}
for (let i = 1; i < 8; i++) {
let element =document.getElementById(`a${i}`).value;
}

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.

Regex: ccTLD wildcard detection/removal in Javascript?

I have an url like this one:
http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
But the ".com" over there can change depending on the country, so that url also works with:
http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
etc.
What I need to do is replacing "xenodesystems.blogspot.*" with "blog.xenodesystems.com" and leave the rest of the URL intact, like this:
http://blog.xenodesystems.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
Is this possible to do with javascript? I know blogger can redirect a domain, but I need to do it in pure Javascript explicitly. I know it's possible, it's just matter of finding the right regex, right?
Try this (JSFIDDLE). No regular expressions so it's much more efficient:
var str="http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html";
function xIndexOf(Val, Str, x)
{
if (x <= (Str.split(Val).length - 1)) {
Ot = Str.indexOf(Val);
if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }
return Ot;
}
}
var slash = (xIndexOf('/',str,3));
var dot = (xIndexOf('.',str,2));
str = str.substring(0,dot)+".com"+str.substring(slash)
alert(str)
xIndexOf function taken from here.
I think this is what you mean:
var urls = [
'http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.com.au/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
];
var ret = new Array;
var len = urls.length;
for (var i = 0; i < len; ++i) {
ret.push(urls[i].replace(/xenodesystems.blogspot(?:\.[a-zA-Z]+)+/,'xenodesystems.blogspot.com'));
}
console.log(ret);
OUTPUT
["http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html"]
Here's a fiddle

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