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());
}
Related
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);
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");
This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
i would like to know how to loop all of my sql datas (that i parsed into a json table) into an array, with adding a key to each of them.
I know how i can loop all of the data into an simple string like this :
var dbString ="";
for(i = 0; i < result.response.length; i++)
{
dbString += result.response[i].names;
}
This would just look like this
var dbString = "James Michael Alfred....";
But how can i make this look like this :
var dbString = {"James":1, "Michael":2, "Alfred":3, .....}
Thanks.
It's a really unique demand to organise a list of names like you want, but here it is:
var dbString = {};
var names = result.response;
for(var i = 0; i < names.length; i++){
dbString[names[i]] = i + 1;
}
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).
This question already has answers here:
is the + operator less performant than StringBuffer.append()
(13 answers)
Closed 9 years ago.
I have two jQuery variables. Each variable is a text string containing words separated by a comma.
var myFirstVariable = green,blue
var mySecondVariable = circle,triangle
I would like to have a third variable retured like this:
var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle
The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if
var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square
Then I need my third variable to returned like this:
var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare
I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.
I'm struggling with this area of jQuery
That's simply because the jQuery library has no tools for this kind of work.
Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:
var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";
var firstArr = myFirstVariable.split(","),
secondArr = mySecondVariable.split(","),
thirdArr = [];
for (var i=0; i<firstArr.length; i++)
for (var j=0; j<secondArr.length; j++)
thirdArr.push(firstArr[i]+secondArr[j]);
var myThirdVariable = thirdArr.join(",");
You can use the plain old string split method to get 2 arrays.
http://www.w3schools.com/jsref/jsref_split.asp
You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string.
http://www.w3schools.com/jsref/jsref_join.asp
Try
var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'
var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)
function fn(fv, sv){
var fa = fv.split(','), sa = sv.split(','), ta = [];
for(var i = 0; i < fa.length; i++){
for(var j = 0; j < sa.length; j++){
ta.push(fa[i] + sa[j])
}
}
return ta.join(',')
}
Demo: Fiddle
OK so you don't need jquery to achieve this, just JavaScript.
check out this answer here to help you:
How to merge two arrays in Javascript and de-duplicate items