this works in PHP:
$i = 4;
$fruit4 = 'apple';
$answer = $fruit{$i};
echo $answer; // apple
so i hoped this would work in javascript:
var i = 4;
var fruit4 = 'apple';
var answer = fruit{i};
print(answer);
but no luck! is there a way to do this using javascript?
NOTE: i realize this is more easily done with an array (var fruit[4] = 'apple') but that isn't an option this time due to pre-existing constraints.
thanks in advance!
JavaScript has a way of accessing properties via square bracket notation so that you can use strings and variables to get to them.
For example, if your fruit4 (From the code in your post) is in the global scope in the browser:
var answer = window['fruit' + i];
Javascript has an function called eval, so try to use it.
For example
var answer = eval("fruit"+ i);
eval('var answer = fruit' + i);
Related
It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.
I am trying to create a new jQuery variable from some text and another jQuery variable.
This is what I have tried but it just displays "+emc+" instead of the value that the variable is set to.
var emc = $(".emc").attr("value");
var new_page = "index.php?emc=+emc+";
The new_page variable should display index.php?emc=XXXXXX but instead it displays as index.php?emc=+emc+
If I've understood correctly:
var new_page = "index.php?emc="+emc;
Or, indeed:
var new_page = "index.php?emc="+$(".emc").val();
You made a mistake in your string concatenation. You wanted to do this:
var new_page = "index.php?emc="+emc;
You have included the variable in the constant your code must look like:
var emc = $(".emc").attr("value");
var new_page = "index.php?emc="+emc;
I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );
I'm trying to create a for loop that does the exact same thing as this code (quests is an array):
Quest0.text = quests[0]
Quest1.text = quests[1]
Quest2.text = quests[2]
Quest3.text = quests[3]
Quest4.text = quests[4]
Quest5.text = quests[5]
Quest6.text = quests[6]
Quest7.text = quests[7]
Quest8.text = quests[8]
Quest9.text = quests[9]
Quest10.text = quests[10]
Quest11.text = quests[11]
Quest12.text = quests[12]
Quest13.text = quests[13]
Quest14.text = quests[14]
Quest15.text = quests[15]
So far all I've got is this (activeQuests is the length of the array quests):
var q = 0;
for (q=0; q <= activeQuests; q++) {
Quest0.text = quests[q]
}
But I don't know how to get it to do the rest.
You could use eval but you probably shouldn't. You should probably rethink your approach if you have such obviously array-like data that you are manipulating manually element by element.
Check out this blog post from Marco van Hylckama Vlieg: "Variable Variables in Javascript". Relevant snippet:
...using the fact that all global variables are held in the window
array.
var i=1;
window['name' + i] = 'Marco';
document.write('got ' + name1);
There we go! Nice, clean and no eval() necessary."
We'd need to know more to give you exact code, but in order to address a variable by string, it needs to be a property of an object. For example
window.example = 'hello world';
alert(window['example']);
So it really depends on what your QuestN variables are. Are they id's of <input> elements? Are they global variables? Are they defined in local scope with the var keyword?
If you can change how Quest.. are defined then define them as an array so you can do:
Quest[q].text = quests[q];
if you can't then temporarily create an array of Quest.. objects:
var QUESTS = [];
QUESTS[0] = Quest0;
QUESTS[1] = Quest1;
QUESTS[2] = Quest2;
QUESTS[3] = Quest3;
QUESTS[4] = Quest4;
QUESTS[5] = Quest5;
QUESTS[6] = Quest6;
QUESTS[7] = Quest7;
QUESTS[8] = Quest8;
QUESTS[9] = Quest9;
QUESTS[10] = Quest10;
QUESTS[11] = Quest11;
QUESTS[12] = Quest12;
QUESTS[13] = Quest13;
QUESTS[14] = Quest14;
QUESTS[15] = Quest15;
Then you can do:
for (var q=0; q<=activeQuests; q++) {
QUESTS[q].text = quests[q]
}
Obviously this is an uglier solution but much better than eval IMHO.
I think you are better off keeping the "quests" array than defining a different variable to each index.
However if you want to loop try eval("Quest" + q + ".text = quests[q]") in the loop.
I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup:
function content(cur){
var mycur = $H(cur);
var pars = "p="+mycur.toJSON();
new Ajax.Updater('my_box', 'test.php', {
parameters: pars
});
}
function update(){
if(window.location.hash.length > 0){
content(window.location.hash.substr(1)); // Everything after the '#'
}
}
var curHashVal = window.location.hash;
window.onload = function(){
setInterval(function(){
if(curHashVal != window.location.hash){
update();
curHashVal = window.location.hash;
}
},1);
}
But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of.
Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done.
Thanks for the help!
EDIT: As an end result, I'd like the URL (say product:3,confirmed:1) to be returned as {"product":3,"confirmed":1}
A typical implementation of toJSON() needs either an Array or an Object as the top-most element. Sonsomethig like this will probably work:
var pars = {p: myCur};
pars = pars.toJSON();
First of all native JSON support and the toJSONmethod is not available in all browsers. Older browsers like IE 6/7 or Firefox 2/3 do not support it. You should use a JSON library like json2 by Douglas Crockford. Second I would suggest to use the stringify method of the global JSON object instead of the toJSON function. In my tests
JSON.stringify("...")
works just fine.
If anyone is still looking for my answer, here's the solution!
function build_json(str){
var new_str = "{";
var cut = str.split(",");
for(var x=0; x < cut.length; x++){
if(x > 0){new_str = new_str+",";}
var s = cut[x].split(":");
new_str = new_str+"\""+s[0]+"\":\""+s[1]+"\"";
}
return new_str+"}";
}