How can i change the variable name in javascript? [duplicate] - javascript

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed last year.
I have some js code like this:
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(parameter+number);
}
selectValue(2);
Here is a fiddle - https://jsfiddle.net/frwd2qLg/
This code will not work, because, for example, for number = 2, it will not show 33333, but will be undefined. Any workaround?

As people said in your comments, you could use an array or an object to do this task. But answering your question you culd use an eval to access the variable name.
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(eval("parameter"+number));
}
selectValue(2);

Related

How to get the value of a variable from a object in JavaScript? [duplicate]

This question already has answers here:
Javascript: How to use Template Literals with JSON?
(4 answers)
Closed 2 years ago.
I am having the object config and when I fetch the config["RegionId"], it will give me ${Region}. Now I want to fetch the value of Region. As I have got ${Region}, I thought I could do console.log(`${val}`) to get 'abc'. But it is not working.
How to get this? This is what I have tried,
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(`${val}`)
Don't put double quotes around the property value. Use back-ticks (for template literal strings) as you are doing for val. And make sure you've declared Region prior to attempting to access it.
var Region = 'abc';
var config = {
"RegionId" : `${Region}`
};
var val = config['RegionId'];
console.log(`${val}`);
And while your question is centered around template literals, I hope you know that for this scenario, they add no value and are overkill. Here's the same thing with regular strings variables:
var Region = 'abc';
var config = {
"RegionId" : Region
};
console.log(config['RegionId']);
try using eval function
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(eval("`"+val+"`"));

How to declare a lot a document.getElementById variables at the same time [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I declared some variables:
var availableTile1 = document.getElementById("c1");
var availableTile2 = document.getElementById("c2");
var availableTile3 = document.getElementById("c3");
var availableTile4 = document.getElementById("c4");
var availableTile5 = document.getElementById("c5");
var availableTile6 = document.getElementById("c6");
As you see, only the number is different. Is there a quicker and clearer way of defining all variables at once?
Note: I heard about "destructuring assignment", but I couldn't apply it with document.getElementById.6
Thank you for your answers.
EDIT:
availableTile.style.border = "none";
availableTile.style.backgroundColor = "transparent";
This works if availableTile is an Id, but somehow not if it is a class?!
Don't use variables. Do use an array. Populate it in a loop.
var available_tiles = [];
for (var i = 1; i <=6; i++) {
available_tiles.push( document.getElementById("c" + i) );
}
You could get a similar result by changing the HTML to make every element a member of the same class. You can then get an array-like object with
var available_tiles = document.getElementsByClassName("tile");
or
var available_tiles = document.querySelectorAll(".tile");

Variable in a variable name? Looping said variables? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
So I have a chunk of code... and I want to make it more efficient by condensing it to a few lines instead of twelve. The idea I had was to use the variable of a loop to call each variable in sequence, since the code is just repeated with different numbers each time. Is there any way this could work?
var usetext1 = getText("text1");
var usetext2 = getText("text2");
var usetext3 = getText("text3");
var usetext4 = getText("text4");
var usetext5 = getText("text5");
var usetext6 = getText("text6");
usetext1 = usetext1.toUpperCase();
usetext2 = usetext2.toLowerCase();
usetext3 = usetext3.toLowerCase();
usetext4 = usetext4.toLowerCase();
usetext5 = usetext5.toLowerCase();
usetext6 = usetext6.toLowerCase();
Reduced to something like:
for (var i=2;i<6;i++){
var usetext[i]=getText("text[i]");
usetext[i]=usetext[i].toLowerCase();
You can use Template Literals to store the value into an array
var arr = [];
for (var i=1; i <= 6; i++){
arr.push(getText(`text${i}`).toLowerCase());
}

Elements and functions separated by commas [duplicate]

This question already has answers here:
What does variable declaration with multiple comma separated values mean (e.g. var a = b,c,d;)
(2 answers)
Closed 9 years ago.
What does this syntax means?
var _t = this, _resetProperties, _add_html5_events, _remove_html5_events, _stop_html5_timer, _start_html5_timer, _attachOnPosition, _onplay_called = false, _onPositionItems = [], _onPositionFired = 0, _detachOnPosition, _applyFromTo, _lastURL = null, _lastHTML5State;
It's just a bunch of variable declarations/initializations, separated by commas. It's the same as:
var _t = this;
var _resetProperties;
var _add_html5_events;
var _remove_html5_events;
var _stop_html5_timer;
var _start_html5_timer;
var _attachOnPosition;
var _onplay_called = false;
var _onPositionItems = [];
var _onPositionFired = 0;
var _detachOnPosition;
var _applyFromTo;
var _lastURL = null;
var _lastHTML5State;
I don't like to mix initializations with declarations like this. It is messy and not very readable. If anything, group your declarations (without values), and only group initializations if they are related. It doesn't functionally change the code, it only makes it a bit smaller (and harder to read in cases).

How to extract a GET parameter from the URL in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use the get parameter of the url in javascript
Suppose I have this url:
s = 'http://mydomain.com/?q=microsoft&p=next'
In this case, how do I extract "microsoft" from the string?
I know that in python, it would be:
new_s = s[s.find('?q=')+len('?q='):s.find('&',s.find('?q='))]
I use the parseUri library available here:
http://stevenlevithan.com/demo/parseuri/js/
It allows you to do exactly what you are asking for:
var uri = 'http://mydomain.com/?q=microsoft&p=next';
var q = uri.queryKey['q'];
// q = 'microsoft'
(function(){
var url = 'http://mydomain.com/?q=microsoft&p=next'
var s = url.search.substring(1).split('&');
if(!s.length) return;
window.GET = {};
for(var i = 0; i < s.length; i++) {
var parts = s[i].split('=');
GET[unescape(parts[0])] = unescape(parts[1]);
}
}())
Think this will work..

Categories