array undefined after pushing to object - javascript

I'm pushing an object into an array of objects. One of the properties of the object (which is an array) is showing up as undefined, after the object is pushed to the array. If you look at my code below, where it says, "WHY IS THIS SHOWING IN CONSOLE?" - it doesn't make sense because if the array is undefined, it should have been undefined in both of the previous two checks (where it says "THIS IS NOT SHOWING IN CONSOLE."). This is driving me crazy. SOS. Please help.
var pathCopy = unit.path; // THIS IS AN ARRAY AND IT IS NOT EMPY
var directionCopy = unit.direction;
if (pathCopy.length < 1) {
console.log('THIS IS NOT SHOWING IN CONSOLE');
}
var object = {
'type': 'move',
'time': gameTime,
'name': unit.name,
'vector': pathCopy,
'direction': directionCopy
};
currentGameEvents.push(object);
if (object.vector.length < 1) {
console.log('THIS IS NOT SHOWING IN CONSOLE');
}
for (var i = 0; i < currentGameEvents.length; i++) {
if (currentGameEvents[i].vector.length < 1) {
console.log('WHY IS THIS SHOWING IN CONSOLE??');
}
}

I’m not sure how or why, but your example works, if I insert the undefined variables (i.e. I replaced unit.path with [345,34623,52] or something that is an array literal).
The only difference to that is, that you actually assign the reference to that array, instead of declaring a new array.
var pathCopy = unit.path; // pathCopy and unit.path are the SAME array
var pathCopy = [345,346,345]; // pathCopy is a completely NEW array
To fix this, try something like
var pathCopy = unit.path.slice(); // pathCopy is a completely NEW array that contains the same values as unit.path
whenever you want to copy an array; add .slice() at the end!
Again, this is deducing from the only difference between your code and what I tried, and this is probably the reason, why your code doesn’t work.
Another assumption is that currentGameEvents is an Array. Your code wouldn’t work at all, otherwise. I’m mentioning this because the title states that you were trying to push to an object, which isn’t possible.

Related

find item in array with object properties

I'm trying to check if something exists in an array.
here is where I make the object...
function makeEventObject(eventName, idzName, classzName) {
function eventDetails(eventName, idzName, classzName) {
this.eventName = eventName;
this.idzName = idzName;
this.classzName = classzName;
}
let eventObject = new eventDetails(eventName, idzName, classzName);
console.log(Object.getOwnPropertyNames(eventObject));
console.log(eventObject.idzName);
// console.log(eventObject);
return eventObject;
}
I can access the eventObject.keys or eventObject.properties >> console.log
The thing I can't figure out, is, I want to push it to an array. But with conditions. If its already in the array, then don't add. But the conditions are also based on on other eventObject.properties. for example: the 1st check is to see if it exists in the array. Because the array is empty initially it should return = undefined, SO add the 1st item. But when the second item comes through, if the eventObject.idZName && the eventObject.classzName is the same as the 2nd do NOT add. if, the .idZname is different, and the .classZname is the same, replace the array element with same .classZname. if the both the .classZname and .idZname are different from what's in the array or undefined. ADD.
its a series of filters, that I came to see to get functional. below are the push to array functions and checker functions. I tried to put both into the same function, but i kept getting .push() errors.
function makeEventList(eventObject) {
eventList.push(eventObject);
console.log(eventList);
let a = eventList.length;
console.log(a);
}
function eventChecker(eList, eventObject){
var exists = eList.find(function(eventObject){return eventObject.eventName === eList[eventObject.eventName];});
console.log(exists);
}
Any Ideas...and what I'm doing wrong? so far tried IF statements, .includes(), .filter(), .each().
currently I'm getting cannot read property of 'find;..
a live copy is available at fiddle -> https://jsfiddle.net/j1xtvmLy/461/
Based on your jsfiddle eList is undefined because you didn't pass in arguments into eventChecker call.
Make sure that when you're relying on parameters that you pass in arguments in the function call.
Also your let eList = makeEventList(eventObject); assumes that it'll return an array but you haven't created or returned the array in your function makeEventList

jQuery - using global array and wait for $get to load retrieved data?

Been struggling all day with looking at code examples and can't get this to work.
Basically I want to load an array using the HTML from four local files.
Then I'll use that HTML to fill a div dynamically with some kind of animated slider.
My problem is that I can't seem to get the timer to wait for the html to be retrieved and assigned to the variables. The GET is working great, but the variables don't seem to be loaded outside the GET loop.
I can see the asynch GET filling the array properly, but the elements remain undefined in the loop. I think they're global variables so it shouldn't be that.
I'm new at jQuery and have been using SO for examples, so open to any suggestions - hopefully this is just an obvious fix for an experienced javascript coder.
Here's my code:
window.standings = new Array(4);
window.iURL = 0;
standingsURL = ["MondayNight.html", "TuesdayNight.html", "WednesdayNight.html", "ThursdayNight.html"]
for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
$.get(standingsURL[window.iURL], function( data ) {
window.standings[window.iURL] = data;
alert (window.standings[window.iURL]);
}, "text");
}
setTimeout(function repeatTimeout() {
if(window.standings[window.standings.length] !== undefined){
for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
alert (window.standings[window.iURL]);
}
} else {
alert ("Wait again");
setTimeout(repeatTimeout, 2500);
}
}, 1000);
The first issue I can see is that in your repeatTimeout function, you're referencing an item in your array that doesn't exist.
window.standings[window.standings.length]
which is equivalent to window.standings[4]
You have an array with four items in it, and you're referencing array index 4 here - but arrays are zero-indexed, so only indexes 0, 1, 2, and 3 are valid. Try:
window.standings[window.standings.length - 1]
Edit:
Declare an empty array:
window.standings = []
Instead of: window.standings[window.iURL] = data;, do this:
window.standings.push(data)
Your if function now checks for length:
if(window.standings.length === 4)
This is a relatively crude solution. Check out this SO post for more information about the when function.

Passing array of objects to a js function

i am trying for the first time to implement OOP in javascript and i got stuck on a recursive function when i try to send an array of objects to this function. So, i have the "Pitic" class (pitic means midget in romanian) with some propreties:
function Pitic(piticID) {
this.id = piticID;
this.inaltime = null;
this.greutate = null;
this.genereazaGreutate();
this.genereazaInaltime();
}
I'm now generating some midgets and storing them in the public piticiCollection Array variable. The "genereazaGreutate" and "genereazaInaltime" are function to generate random values for the inaltime and greutate values.
var pitic = new Pitic(idPitic);
piticiCollection.push(pitic);
The problem appears when i try to send the array of midgets to a function because all i get is only the first item of the array.
So, before i call the function, i have piticiCollection array with 4 objects:
midgets are safe and sound http://img443.imageshack.us/img443/484/yr4f.png
And as soon as i call the function with the piticiCollection as a parameter i loose 3 midgets! :(
most of the midgets are gone http://img201.imageshack.us/img201/5808/7od5.png
p.s. please excuse me for my bad english..
[EDIT]
Here is a fiddle of my full code: http://jsfiddle.net/WT7Ud/ I call the function on line 56 and as soon as the debugger hits line 60 i loose array items.
I have solved my problem by creating a copy of the array before using it in the function. Strange :(
function determinaPerechi(somePitici) {
var piticDeComparat, colectieDePiticiCopy;
colectieDePiticiCopy = somePitici;
for (var i = 1; i < colectieDePiticiCopy.length; i++) {
var piticDeComparat2 = null;
piticDeComparat = colectieDePiticiCopy[0];
piticDeComparat2 = colectieDePiticiCopy[i];
if (piticDeComparat.inaltime < piticDeComparat2.inaltime) {
//Perechea poate fi prietena
}
}
//colectieDePiticiCopy.splice(0, 1);
if (colectieDePiticiCopy.length == 0) {
//alert("finish");
return;
}
determinaPerechi(colectieDePiticiCopy);
//test(ttt);
}
Your determinaPerechiPosibile is modifying the original array on this line:
colectieDePitici.splice(1, colectieDePitici.length);
In particular, it is removing all but the first element. You probably should be using slice to non-destructively extract the part of the array you want to recurse on.
As Ted Hopp mentioned, the problem appears to be the line
colectieDePitici.splice(1, colectieDePitici.length);
in combination with this line:
determinaPerechiPosibile(colectieDePiticiCopy);
If those two lines are commented out, the array maintains its original length.

Can I loop through 2 objects at the same time in JavaScript?

related (sort of) to this question. I have written a script that will loop through an object to search for a certain string in the referring URL. The object is as follows:
var searchProviders = {
"google": "google.com",
"bing": "bing.com",
"msn": "search.msn",
"yahoo": "yahoo.co",
"mywebsearch": "mywebsearch.com",
"aol": "search.aol.co",
"baidu": "baidu.co",
"yandex": "yandex.com"
};
The for..in loop I have used to loop through this is:
for (var mc_u20 in mc_searchProviders && mc_socialNetworks) {
if(!mc_searchProviders.hasOwnProperty(mc_u20)) {continue;}
var mc_URL = mc_searchProviders[mc_u20];
if (mc_refURL.search(mc_URL) != -1) {
mc_trackerReport(mc_u20);
return false;
}
Now I have another object let's call it socialNetworks which has the following construct:
var socialNetworks = {"facebook" : "facebook.co" }
My question is, can I loop through both of these objects using just one function? the reason I ask is the variable mc_u20 you can see is passed back to the mc_trackerReport function and what I need is for the mc_u20 to either pass back a value from the searchProviders object or from the socialNetworks object. Is there a way that I can do this?
EDIT: Apologies as this wasn't explained properly. What I am trying to do is, search the referring URL for a string contained within either of the 2 objects. So for example I'm doing something like:
var mc_refURL = document.referrer +'';
And then searching mc_refURL for one of the keys in the object, e.g. "google.com", "bing.com" etc. 9this currently works (for just one object). The resulting key is then passed to another function. What I need to do is search through the second object too and return that value. Am I just overcomplicating things?
If I understand your question correctly, you have a variable mc_refURL which contains some URL. You want to search through both searchProviders and socialNetworks to see if that URL exists as a value in either object, and if it does you want to call the mc_trackerReport() function with the property name that goes with that URL.
E.g., for mc_refURL === "yahoo.co" you want to call mc_trackerReport("yahoo"), and for mc_ref_URL === "facebook.co" you want to call mc_trackerReport("facebook").
You don't say what to do if the same URL appears in both objects, so I'll assume you want to use whichever is found first.
I wouldn't create a single merged object with all the properties, because that would lose information if the same property name appeared in both original objects with a different URL in each object such as in an example like a searchProvider item "google" : "google.co" and a socialNetworks item "google" : "plus.google.com".
Instead I'd suggest making an array that contains both objects. Loop through that array and at each iteration run your original loop. Something like this:
var urlLists = [
mc_searchProviders,
mc_socialNetworks
],
i,
mc_u20;
for (i = 0; i < urlLists.length; i++) {
for (mc_u20 in urlLists[i]) {
if(!urlLists[i].hasOwnProperty(mc_u20))
continue;
if (mc_refURL.search(urlLists[i][mc_u20]) != -1) {
mc_trackerReport(mc_u20);
return false;
}
}
}
The array of objects approach is efficient, with no copying properties around or anything, and also if you later add another list of URLs, say programmingForums or something you simply add that to the end of the array.
You could combine the two objects into one before your loop. There's several approaches here:
How can I merge properties of two JavaScript objects dynamically?
var everything = searchProviders;
for (var attrname in socialNetworks) { everything[attrname] = socialNetworks[attrname]; }
for(var mc_u20 in everything) {
// ...
}
for (var i = 0; i < mc_searchProviders.length; i++) {
var searchProvider = mc_searchProviders[i];
var socialNetwork = mc_socialNetworks[i];
if (socialNetwork != undefined) {
// Code.
}
}
Or am i horribly misunderstanding something?

Javascript - storing the index of all array values in a variable

Say I have an array in JS: var fruits = [apple,orange,banana]
I want to store the index of each fruit in variables such that at any point in time, if I add more stuff to the array, I will still know that the index of apple is X. So in this case, 0 is apple, but if I add something to the beginning of that away, the index of apple changes.
The more verbose way I can think of is to loop through the array
for (var i=0;i<fruits.length;i++) {
switch(fruits[i]) {
case:"apple"
var indexApple = i;
break;
//etc
}
}
Another way I can think of is use the value of the arrays as the variable name.
for (var i=0;i<fruits.length;i++) {
//psedo code
var 'index' + fruits[i] = i;
}
So in the end I'd have var indexApple = 0, indexOrange = 1, etc. THe key to the second method is to be able to create a dynamic variable by concatenating the string 'index' and the value of the array to create that variable. Not sure how to do that.
Note: Ideally I want the variables that store the index to be dynamically generated. Such that I only I can modify/add to the fruits array, and a new variable will be generated to store the index.
it seems like ensuring your the value of the index is legitimate will be difficult. i would include jquery and use the inArray method which returns the index of the item in the array.
function showIndexes() {
var appleIndex = $.inArray(fruits, "Apple"); //returns 0
var guavaIndex = $.inArray(fruits, "Guava"); //returns -1
fruits.unshift("Guava");
appleIndex = $.inArray(fruits, "Apple"); //returns 1
guavaIndex = $.inArray(fruits, "Guava"); //returns 0
}
The simplest solution is simply to build an Object which gives you nearly O(1) lookup time, and will scale with your array:
function LinkFruits(fruits) {
FruitLookup = {}
fruits.forEach((fruit,ind) => FruitLookup[fruit] = ind)
}
Now you can simply "lookup" your index from the FruitLookup table when needed like:
console.log("The index of apple is",FruitLookup.apple,"and for orange is",FruitLookup.orange)
Now if you modify your array you simply need to run LinkFruits(fruits).
Technical Note: If you want to fully automate this process you can look into Array.observe() which is now deprecated. Or overload the push and pop methods of this array to trigger the update before falling back to the default prototype methods.

Categories