Create variable from array keys in JavaScript - javascript

Is there a way to make a variable using an array value? For ex.
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
var noteSharp[x] + "Sharp" = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
var noteFlat[x] + "Flat" = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
If I do a console.log(CSharp) it says that CSharp is not defined.
In this example I am trying to define a total of 24 variables. Some variable name examples im expecting to get are ASharp , A#Sharp , BbFlat , DFlat. The CSharp and CFlat variable should both be "CDEFGAB"
If this is not possible is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.

If you want to make a global variable, attach it to window
window[variableNameHere] = itsValue;
In your case:
window[noteSharp[x] + "Sharp"] = noteSharp[x] + ...
But it's not good to pollute the global namespace. How about putting it in another namespace:
var sharps = {};
var flats = {};
sharps[noteSharp[x] + "Sharp"] = noteSharp[x]...
flats[noteFlat[x] + "Sharp"] = noteFlat[x]...
//access them
sharps.ASharp;
I quite can't figure out what your code does, but this solution should point you to the right direction.

try the following code
var noteSharp = ["A","B","C"];
for(i in noteSharp) {
window[noteSharp[i]] = 'value of '+noteSharp[i];
}
alert(A)
alert(B)
alert(C)
This is exactly what you want.
and rewriting it for your code
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
window[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
window[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
alert(ASharp);
alert(AFlat);

As per my knowledge, in JavaScript there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var times = 1;
eval("var sum" + times + "=10;");
alert(sum1);
window object:
var times = 1;
window["sum" + times] = 10;
alert(window["sum1"]);

Change the end of your code to look like this:
for (var x=0; x<12; x++){
self[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
self[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
As a result, you will have global variables with variable names like you want, such as CSharp, which would equal "CDEFGAB"--however, complicated variable names like A#Sharp cannot be written outright as variables, but can still be accessed by using subscript notation, like this self["A#Sharp"] (or window["A#Sharp"] in most cases, although it has traditionally been better style to use self rather than window to refer to the most local window object connected with a script instance).
The other answer looks like it has been finished out by the time I finished typing mine, and it looks good, too.

If this is not possible
It isn't for local variables without the use of eval.
is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.
No. It's not possible because ECMA-262 specifies that the only way to declare a variable is by a variable declaration statement, which is of the form:
var *identifier* [optional initialiser]
where identifier is a valid identifier, which can't be an expression like:
var 'foo' + 'bar';
The rest of the question has been covered in other answers.

Related

How to document.write multiple variables at once?

I have a loop that will declare a new variable each time. I want to write my results to a new window and I would like every string declared to print with breaks.
I did try making combining all vars together with '+' signs (using [i] to get the number of occurrences) but document.write printed it because it was a string.
Does anyone know what I can do? I'm sure there must be a few ways but I've been stuck on this for a while.
window['question'+i] = "some stuff";
var myWindow = window.open("", "Questions", "width=500,height=600");
myWindow.document.write(
question0 + ("<br>") +
question1 + ("<br>") +
question2 + ("<br>") +
question3 + ("<br>")
...
)
I recommend to not use different variables. Array's are made for these kind of things and provide functions to do this a lot easier. See this snippet below how to store the texts from a loop in an array and easy print it splitted by a <br> using the join function.
var values = new Array();
for (var i = 0; i < 10; i++) {
values.push("<span>value " + i + "</span>");
}
document.getElementById('result').innerHTML = values.join("<br>");
//If you really want to use document.write()
//document.write(values.join("<br>"));
<div id="result"></div>

Javascript syntax error? "Unexpected Indentifier"

sorry I just started with javascrippt and html and I am having trouble finding out what the unexpected identifier is?
here is my function
function fillSearchPlayer(data){
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i]
var item = '<tr><td>'p.firstname + ' ' + p.lastname'</td><td>'p.job'</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>'
$('#searchPlayers tbody').append('item');
}
}
maybe you guys could help me, it's saying its coming from the line that starts with "var item"
'<tr><td>'p.firstname look like you missed a plus sign over there. The other thing is .append('item'); - you probably intented to do .append(item);.
As the guys mentioned in the direct comments above you should try to use some templating engine instead of constructing the strings the way you did it.
I would recommend you to read these pieces:
Handlebars - simple and convenient template engine in JavaScript - give it a try!
Template strings in ES2016 - a cleaner way to do what you did with manual string concatenation
There are several errors. String concatenation works with +, and you're missing a semicolon.
Try:
function fillSearchPlayer(data) {
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i];
var item = '<tr><td>' + p.firstname + ' ' + p.lastname + '</td><td>' + p.job + '</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>';
$('#searchPlayers tbody').append('item');
}
}
The var item = ... item mixes variable and literal definitions without the real concatenation going on. Just put a + between each varying element to achieve your goal.
You need to enclose the concatenation operator around the p.job variable.
Your assignment should look like this...
var item = '<tr><td>'+p.firstname + ' ' + p.lastname+'</td><td>'+p.job+'</td><td><button class="cbtn" onclick=requestPlayer('+ p.identifier + ')>More</button></td></tr>'

Dynamically setting variables in javascript

Trying to dynamically set variables depending how many vimeo iframes are on my page. Im using the Eval method in my code below:
var numberVimeoFrames = jQuery(".vimeo").length;
for(i=1;i<=numberVimeoFrames;i++){
var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
eval("player" + i + "= new Vimeo.Player(" + refFrame + ")");
}
My eval line is however generating an error message:
Uncaught SyntaxError: Unexpected identifier
To me it looks like ive concatenated correctly so not sure where ive gone wrong?
Even though in this case I do not think it is that bad, the general opinion is to not use eval at all.
Use arrays instead :
var numberVimeoFrames = jQuery(".vimeo").length;
var players = [];
for(i=1;i<=numberVimeoFrames;i++){
var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
players.push(new Vimeo.Player(refFrame));
}
You can now access your players by calling the array (for example players[1] instead of player1 and so on.)

Extract string html with regex on interval

There is a public website with this in the source:
</div><script type="text/rocketscript">
function calculateIndexIncome() {
var khs = $('#t9').val();
var btcusd = $('#t9_1').val();
var btckhs = $('#t9_2').val();
var dayprofitperkhs = 0.00000018188885404454654
var arr = btcusd.split(' ');
btcusd = arr[0];
var totalinvestmentusd = ((khs * btckhs) * btcusd).toFixed(2);
var totalinvestmentbtc = (khs * btckhs).toFixed(8);
var dailyincomebtc = (khs * dayprofitperkhs).toFixed(8);
var dailyincomeusd = ((khs * dayprofitperkhs) * btcusd).toFixed(2);
var monthlyincomebtc = (dailyincomebtc * 31).toFixed(8);
var monthlyincomeusd = (dailyincomeusd * 31).toFixed(2);
var breakevendays = (totalinvestmentusd / dailyincomeusd).toFixed(0);
var monthlypercentage = ((100 / breakevendays) * 30).toFixed(2);
$('#tl').html('Total KHS: ' + khs + '<br/>Total Investment: ' + totalinvestmentbtc + ' BTC ($' + totalinvestmentusd + ' USD)<br/><br/>Daily Income: ' + dailyincomebtc + ' BTC ($' + dailyincomeusd + ' USD)<br/>Monthly Income: ' + monthlyincomebtc + ' BTC ($' + monthlyincomeusd + ' USD)<br/><br/>Break Even In: ' + breakevendays + ' Days.<br/><br/>Monthly Rate: ' + monthlypercentage + '%');
}
I need to be able to extract two values: btckhs and dayprofitperkhs.
if I look at page source, dayprofitperkhs is different everytime I refresh.
Edit:
Jimmy Chandra came up with this bookmarklet:
javascript:
setInterval(logging,60000);
w1 = window.open("https://scrypt.cc/index.php");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'https://scrypt.cc/index.php';
}
This works ALMOST perfectly. it gets the dayprofitperkhs, but only on the first interval.
After that, the value is no longer updated, although t9_2 IS updated...
Anyone?
I don't know where that site is, so I am just running this against this SO question, but the following bookmarklet is getting me what I want...
As I mentioned in the comment, I use Regular Expression against the document body inner html and I am looking for dayprofitperkhs and capturing the numbers and decimal separator on the right side of the equal sign. Also trying to compensate for any extra spaces in between (\s*). RegExp.$1 gave me the number that I am looking for.
javascript:(function(){var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;var matches=re.exec(document.body.innerHTML);console.log(RegExp.$1);}());
So your final bookmarklet should be something like:
javascript:
setInterval(logging,60000);
w1 = window.open("siteurl.com");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(w1.document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'siteurl.com';
}
The variables in question are local variables within the calculateIndexIncome() function, so no, you can't access them from outside that function.
The reason the first one "works" is because you're not referring to the variable, but rather the value: $('#t9_2').val(). This is a jquery selector which finds the element with the ID t9_2 and grabs its value.
You cannot visit it because its a local variable, it only exists in calculateIndexIncome() function.
By the way, you needn't open a new window to visit the variables. You can use chrome dev tools to directly modify the javascript to print the values, or set a breakpoint to debug the code.
Here is a tutorial for chrome dev tools: https://www.codeschool.com/courses/discover-devtools

How do I use Jquery variable variables? [duplicate]

This question already has answers here:
Access Javascript variables dynamically
(4 answers)
Closed 8 years ago.
I know there are a lot of questions about if it is possible to use variable variables in jQuery.
One of the questions is this one: click here.
I tried to use the answer, but I don't know how I can use it in my case.
var numberofquestions = 10;
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
/* ------ first part ------- */
if (i==1) {
dataString = dataString + "q1=" + question1 + "&";
} /* ------ end first part ------- */
else if (i == numberofquestions) {
questionValue = "question" + numberofquestions;
qValue = "q" + numberofquestions;
dataString = dataString + qValue + "=" + questionValue;
console.log(dataString);
} else {
questionValue = question + i;
dataString = dataString + "q" + i + "=" + questionValue + "&";
}
}
The loop will run 10 times, and each time it needs to add a part to the already existing dataString.
What it needs to do is make this string:
q1=(value of var question1)&q2=(value of var question2) and so forth.
The vars question1, question2, ... question10 all hold a number.
The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:
q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10
Does anybody know what I'm doing wrong?
You should use an array for this. There is no such thing as "variable variables" in JavaScript.
You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.
In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.
I'm not sure why you're using "question" + numberofquestions which will be 10 every time

Categories