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.
Related
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)
Knowledge: First week Javascript
I am trying to learn real javascript and avoid jquery at all cost. Now I am I recently learned that id's can be style easily but not classes. In order to style a class I need to loop through the dom for the class. My original code works, however my new one does not. Best practices aside for a moment, I am trying to learn how this works regardless if it is a perfect solution or not.
Problem specifics: In my new code I stored the two get functions in keys within an associative array. So I have objects which I would like my for loop to understand. I am trying to make it work like my first code.
What I tried: Honestly, I read something about squared bracket notation and how it can be useful. I felt a bit overwhelmed to be honest. What I tried was:
source[_class][i]
Maybe _class is undefined even though I defined it. I specified what class contains. Honestly im lost and would appreciate some help and of course I welcome best practice advice as well.
I want to be a better programmer and I would appreciate some insight. I dont want to start with jquery.
My experiment:
setTimeout(function() {
var source = {_id: document.getElementById('box'),
_class: document.getElementsByClassName('hint')};
for (var i = 0; i < source[_class].length; i++) {
source[_class + i].style.opacity = '0';
console.log(i);
}
}, 1000);
My original working code:
// setTimeout(function() {
// var divs = document.getElementsByClassName('hint');
// for (var i = 0; i < divs.length; i++) {
// divs[i].style.opacity = '0';
// console.log(i);
// }
// }, 1000);
Use source._class.length instead of source[_class].length and source._class[i] instead of source[_class + i]:
for (var i = 0; i < source._class.length; i++) {
source._class[i].style.opacity = '0';
console.log(i);
}
source is an object and has a property _class. You can access properties either as source._class or as source['_class'].
The property source._class is an collection of DOM nodes itself so it can be accessed like an array. You can access array elements like this: array[index].
So you have both an object with properties and an array with elements. You need to access their contents appropriately.
Styling should be done with css, not loops, because using css is an order of magnitude faster.
Create css class definitions for your set of styles and then simply change the name of the class on your elements to change their style.
Also, look into using css selectors to query the DOM. This is done with querySelector for a single element, or querySelectorAll for a set of elements. Note that jQuery wraps this functionality and that is where the name is derived.
For your specific example, the problem was with accessing the array, instead of adding the i index, you need to reference the array, and you also need to make sure you are using a string index or a dot notation (such as source._class) in order to reference that object's property
for (var i = 0; i < source['_class'].length; i++) {
source['_class'][i].style.opacity = '0';
console.log(i);
}
You missed a square bracket and it's text not a variable:
source[_class + i].style.opacity = '0';
should be
source["_class"][i].style.opacity = '0';
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic object property name
I have an object like this
var localAppConfig = {
wallet:0,
paySomeone:0,
payBills:0,
accounts:0,
moveMoney:0,
alerts:0,
offers:0,
checkIn:0
};
I want to set value 1 for particular elements within this localAppConfig
Which element needs to be set is retrieved from the json - which arrives from the server.
say, I want to set value = 1 for wallet, paySomeone, payBills, alerts, offers, checkIn
These are retirved from the json like
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = eval('localAppConfig.'+name);
eval('localAppConfig.'+name)=1;
}
var name contains name of the element and I am able to access its value correctly,
How can I set the value using javascript?
I tried accessor=1 but its not working.
Thanks :)
Anyhow: try this on for size:
localAppConfig[name] = 1;//where name is a variable of choice, it's value will be used as the propertyname
And again:
-When all you have is the eval hammer, everything looks like your thumb.
–Brendan Eich in response to: we should encourage use of eval() rather than the Function constructor for dynamic creation of functions.
But why use a list of the properties? you might as well use a for...in loop: in case of objects, like yours, it's perfectly all right. As long as you check .hasOwnProperty, too:
for (var prop in localAppConfig)
{
if (localAppConfig.hasOwnProperty(name))
{
//set, delete... do whatever
}
}
You should do this instead:
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
Try localAppConfig[name] = 1;
It's just a javascript object, no need to use eval() on it.
Don't use eval(). You can add a property by referencing the index of that value within your object. If it doesn't exist then it will be created, otherwise the value will be overridden.
Try the following instead:
// localAppConfig[list[i].handle] = 1;
for(var i=0;i<len;i++){
localAppConfig[list[i].handle] = 1;
}
Or if you intend to reference the variable in another place then set a variable with the value of list[i].handle:
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
}
I have an object called TruckModel which is defined earlier in my JavaScript file called milktruck.js
I'm trying to create an array of these TruckModel objects because I don't know at any given time how many TruckModel objects will be needed as players of my multiplayer game enter and exit.
I know that my current code isn't working because the model won't display when I use the teleportToThat function below.
I was able to get the model to display by declaring only one TruckModel() object in my index.html file and then using the teleportToThat
Here's my code for this, do you see any errors in how I'm doing it?
Non-working version:
var opponentTrucks = [];
for (var i = 0; i < markers.length; i++) {
opponentTrucks[i] = new TruckModel();
opponentTrucks[i].teleportToThat( lat, lng, heading );
}
Working version: (Difference being that I'm trying to have a varying amount of TruckModel objects)
Declared in index.html file:
var model;
Declared in JavaScript file:
model.teleportToThat( lat, lng, heading );
Here's the entire JavaScript file:
http://thehobbit2movie.com/milktruck.js
If you want to be able to find the objects by numeric index, you want an array, not a plain object:
var opponentTrucks = [];
What you've got will work, kind-of, but there's no reason not to use a real array if you're going to treat it like one anyway.
edit — it's still not really clear exactly what the problem is. This line here:
opponentTrucks[i].teleportToThat( lat, lng, heading );
What is that supposed to do? Where is it called from? What's the value of "i"? If you simply have that statement following the loop, then it's not going to work. If you want to have that "teleportToThat()" function called for each one in the array, then you should put the function call inside the "for" loop.
If you're only using numeric keys, you want an array, rather than an object:
var opponentTrucks = [];
for (var i = 0; i < markers.length; i++) {
opponentTrucks.push(new TruckModel());
}
This probably wouldn't stop your code actually working, but it would almost certainly be an improvement.
If there are still errors, perhaps you could say what they are :-)