In a situation where I have something like this code:
var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];
Is there any way I could go through the array and initiate variables with their corresponding values? I've tried something like
for(var i=0;i<variableNames.length;i++){
eval("var "+variableNames[i]+"="+variableValues[i]+";");
}
But I'm not getting any reults. Is eval not able to define variables, or are there other problems that exist? Any solution would be greatly appreciated.
You need to assign the variables on an object. If you want to create global variables the following code should work:
for (var i=0; i<variableNames.length; i++) {
window[variableNames[i]] = variableValues[i];
}
//test
console.log(thisMonth); //"February"
Here you go. You missed a couple of quotes at "='" + variableValues[i] + "';");:
var variableNames=["thisMonth", "thisDay"];
var variableValues=["February", 17];
for(var i=0;i<variableNames.length;i++){
eval("var "+variableNames[i]+"='"+variableValues[i]+"';");
}
With that correction however, I would warn you against using it cause it's a very wrong way of doing it.
Use Objects, as most here mention.
Related
I am trying to find a better solution for adding objects to an array. The box objects are from a separate file and are pushed to the array one line at a time in a different file, as such:
function loadCols(){
collisionPoints.push(box1);
collisionPoints.push(box2);
collisionPoints.push(box3);
collisionPoints.push(box4);
collisionPoints.push(box5);
collisionPoints.push(box6);
collisionPoints.push(box7);
collisionPoints.push(box8);
collisionPoints.push(box9);
collisionPoints.push(box10);
};
I have tried using a for loop and concatenating the string "box" + i but this didn't work.
I also tried adding them to an array in the file where the objects are created but I was not able to find a way of passing the array to the main file. Although this works I'm hoping there is a cleaner solution. Any help would be appreciated, cheers.
You can get a variable from it's string name, by using the window object.
function loadCols(){
for (var i=1; i<=numberOfBoxVars; i++) {
collisionPoints.push(window["box" + i]);
}
}
Alternatively, if your variable are defined within a closure and your loadCols function is defined within the same closure, you can use the "this" keyword in place of the window object.
(function() {
var box1 = "1";
var box2 = "2";
...
function loadCols(){
for (var i=1; i<=numberOfBoxVars; i++) {
collisionPoints.push(this["box" + i]);
}
}
});
If I understand you correctly you are looking for a way to use dynamic variables in a for-loop. If box1 and so on are global variables you can get them dynamically by accessing them as property of window:
window['box'+i]
See here: Use dynamic variable names in JavaScript
If you send all the objects in a JSON array you could just do this:
var array = JSON.parse(boxesarray);
for(var i = 0;i< array.length; i++) {
collisionPoints.push(array[i]);
}
But it would require you sending all the boxes in an array, if this is not possible please post code as to why it isn't and i will adapt my anwser.
I don't think it thinks this is a variable.
I have a global variable dummy1, dummy2, dummy3, etc. I keep getting undefined when I do console.log(dummy1).
I want to append the 1,2,3 to the word dummy and save whatever I have into my global. This isn't working and I don't even think it is efficient but not sure what to do?
for(var i = 1; i<3; i++){
if(numberSelect == i){
window["dummy"[i]]=numberSelect;
}
}
Change to:
window["dummy" + i] = numberSelect;
Try out this approach.
window.CustomStorage = {};
window.CustomStorage["dummy"+[i]]=numberSelect;
And you can retrieve it like
window.CustomStorage.dummy1 or simply CustomStorage.dummy1
So basic idea is you save all your dynamic stuff into a object called CustomStorage and retrieve it by using the property name. ie dummy1, dummy2 etc
I can't believe that I've been unable to dig out a solution to this problem. It looked to me like a very "regular" problem whose solution would litter the web!
I have these arrays returned from a database query:
var ids = ['12', '15', '40'];
var actions = ['hide', 'show', 'fadeIn'];
I want to loop through the arrays and carry out the appropriate action on the DOM, like so:
for(var i=0; i < ids.length; i++){
$('#row_'+ids[i]).actions[i]();
}
Now you get the idea. Actually I didn't expect the $('#row_'+ids[i]).actions[i](); to work as is. I have tried things like
$('#row_'+ids[i]).effect(actions[i]);
To no avail. I believe eval() should work and (in desperation) even tried that but couldn't get the right string for it to work.
Elsewhere on Stack Overflow, I have come across similar issues solved using the window global, like:
var fn = 'hideSomething';
window.fn();//where hideSomething was a defined function.
But this one is defined on jQuery, not on window.
So here we are!
You need to use [varhere] to access a property/method by variable name. Since your property name is in actions[i], then you would do this:
$('#row_'+ids[i])[actions[i]]();
Or, in a slightly easier scheme to follow exactly what is happening:
var method = actions[i];
$('#row_'+ids[i])[method]();
You can use the dot syntax obj.prop when the property name is known ahead of time. When it's in a variable and not known ahead of time, you use the obj[prop] syntax. Since a method is just a property, the same applies to jQuery methods too.
for(var i=0; i < ids.length; i++){
$('#row_'+ids[i])[actions[i]]();
}
Use square bracket notation in order to access the property:
for (var i = 0; i < ids.length; i++) {
$('#row_' + ids[i])[actions[i]]();
}
Example Here
See: Property accessors in JS (MDN)
Is there a nice, clean way to concatenate a string and a variable into a variable name that Jade can understand?
Ideally, it would look something like this:
each #{shape + 'Text'} in #{shape + 'Texts'}
li #{shape + 'Text'}
I tried using window[shape + 'Text'] but that didn't seem to work. Maybe I was doing it wrong?
Here's why I want to do this:
I have an array called shapes that looks like this: ['square', 'triangle', 'circle']
I'm using Jade's each ... in ... function to iterate through this array. Within each iteration of my function, I need to do another each ... in ... of one of a few other arrays. Instead of using a straight-up variable to select which array to iterate over, like each shape in shapes, I want to concatenate shape with a string in order to get something like each squareText in squareTexts or each circleText in circleTexts.
Currently, I'm using conditionals to achieve my desired result, but it's verbose and not in the minimalist spirit of the language.
Thanks in advance for any advice.
So it looks like in my case, the trick is to use Javascript's eval() function to concatenate the variable name and the string into a new variable name. Here's my successful (and succinct) implementation.
- var items = eval(shape + 'Texts');
each item, i in items
li #{items[i]}
I'd suggest looking at an option to create/eval this out of Jade, keep the jade code (and any templare for this matter) as simple as possible.
You can wrap a variable and string in parentheses.
each item, i in items
li=(shape + 'Texts')
I am not exactly following what you are referring to since I don't know jade at all, but you would loop through an array like this.
var a = ['square', 'triangle', 'circle'];
var i, l, item;
l = a.length;
for (i = 0; i < l; i++) {
item = a[i];
// At this point, you can refer to window[item + 'Text']
// but I'm not sure what that is supposed to mean.
}
There is also an Array.prototype.every available, but I usually don't bother to monkeypatch it in to older browsers.
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']