JavaScript items disappearing from Array - javascript

I have an array called objs that holds all of my application objects. Objects get added and removed from this list depending upon what happens in the application.
I am having this problem where some objects disappear (or are overwritten) only sometimes. If I step through the add and remove functions, the app always runs as it should, however many times when it is run without the debugger, one or two objects that were added to the end of the list disappear from the list.
objects are added to the array like this:
this.objs[this.objs.length]=obj;
and are removed from the array like this:
for(var i=0;i<this.objs.length;i++)
if(this.objs[i]==obj)
return this.objs.splice(i,1);
I put this code at the end of my add and remove functions:
console.log("add! ");
console.log(this.objs);
Linked is an image of a console log during a session where an object dissapeared: http://ilujin.com/error.png
The first 4 objects in the list shown at the top should remain in the list throughout the session, but the object at index 3 (highlighted in red), gets overwritten by the next object that gets added (highlighted in blue).
The other weird thing is that the second list shown already has all of the changes (4 objects removed and 1 added), even though the remove function has only been called once and the add function not at all.
This makes me conclude that the problem is timing - if one add hasn't finished before the next add is called, the first one will be overwritten. And all of the console prints are the same because they all happen before the console can read and print.
Does this makes sense? For some reason I thought JS never ran parallel code and only moved on to a new function when the last function finished. Is the problem that I'm using the length of the objs list as the new index when I add to the list?
How can I fix this issue? I can't figure it out, and the debugger and console have proven useless.
Here is the app: http://iioengine.com/neuro/study2.htm
you only need to enter an id and see if the instructions pop up. If they do, than its working and refresh. If they don't, that means that the Text Object got overwritten.

You would really be better served by using Javascript's array methods.
Add to array:
this.objs.push(obj);
Remove from array:
this.objs.splice(this.objs.indexOf(obj), 1);
Also, note that splice edits the original array and returns the elements that have been removed. It's hard to tell from your limited code sample, but that might also be causing issues.

Related

TypeScript: empty array is initialized with values, and those values cannot be changed

Now, this might just be me not knowing some basics of how TypeScript works, as I am pretty inexperienced with it, but all my attempts to find a solution to this issue have so far failed.
In one of my functions I am trying to get an item-by-item disjunction of two boolean arrays. However, when I am initializing an empty array to then fill with new values, something strange happens.
let res = new Array<boolean>();
console.log(res)
Output of the freshly initialized array "res"
As you can see, while array is depicted as empty in its collapsed form, opening it for more info reveals that it actually already has 5 "false" values in it. (note: it is not always 5 falses, this is just an example)
When the function then starts pushing new values into it, while those values are depicted correctly in the array's preview, in reality there are still the same five "false" values inside it, and those are not being changed in any way. Furthermore, logging specific items from this array returns correct values
res.push(a[i] || b[i])
console.log("disjunction at position " + i.toString())
console.log(a[i])
console.log(b[i])
console.log(res[i])
console.log(res)
Console output
This function then returns a new boolean array to be pushed into an array of arrays. When I am logging this array of arrays, it depicts not arrays of values the function filled them with, but instead those weird values that have been put there with initialization. This does not seem to affect the first array (and only that one).
Array of arrays
As I said, I might just miss some crucial information about how arrays in TS/JS work. Right now I am a bit lost, so any help would be appreciated!
Turns out it was just me not knowing how dev console works. The big array of arrays is being filtered after being filled up, and because console shows all the arrays in real time, filter causes it to retrospectively depict them as full of falses. Temporarily removing filter proved this hypothesis.

Javascript 3d array issue

I have these 3 dimensional arrays :
I then try to add a new row to the 2nd dimension using:
drawTable[1].push([0,0,0,0,0,0])
and the array updates to:
I did not expect drawTable[0] to be affected, but looks like it gets a row to, perhaps to keep it "square"?
I then run the following code:
drawTable[1][1]=[1,1,1,1,1,1].
I would expect this to only change one line of 0's, but it seems to change it in drawTable[0] and drawTable1 for some reason.
Can anyone explain this behavior to me?
schteppe was correct. I used drawTable.push(drawTable[0]) to create the second element of the drawTable array. Apparently that makes them mutually dependent?
I changed to:
drawTable[1]=drawTable[0].slice(0,drawTable[0].length)
and the problem went away.

Javascript object loop is only appending the last iterated element to another object

I have a series of loops, within the final loop a javascript object is created. The object changes on each iteration, for example:
// iteration 1: {Belmonte: 0.14625} (index):65
// iteration 2: {Castelo Branco: 0.286} (index):65
// iteration 3: {Belmonte: 0.14625} (index):65
// iteration 4: {Castelo Branco: 0.286}
// ... etc
I want to append each (4) versions of the object to another object, but I am only able to append the final version #4: {Castelo Branco: 0.286}. I understand why this is happening, but can't find a solution. I have created an example (check the console output): http://jsfiddle.net/LUAj3/
UPDATE
I solved the issue by placing i into a function, thus creating its own scope.
I did a very quick look over your jsfiddle, so take what I'm saying with a grain of salt.
In your example, this line catIndicator[pck[i]] remains the same when you loop through your inner loops, since in each iteration of your inner loops the value of i doesn't change, so you're overriding that value.
If I'm understanding your question correctly, you'd need to use multidimensional arrays like catIndicator[pck[i][j][key]]. That may not be the correct order, depending on how you want to set up your data object, but I believe it gets the point across.
Word to the wise, try to keep your examples as small and to the point as possible. Most people on SO will move on to another question if they see the example is too complicated for a quick answer. If you adjust your example so that only the problem code is highlighted, I'm sure you'll get more responses.

How to keep track of the sort index with Knockout-sortable?

I'm using Knockout-sortable to drag-and-drop/sort records in my table, but I've run into a problem. I have no clue how to keep track of the position in the sort index of an element. (I.e. element A, B and C appear in that order and have 1,2,3 as index respectively, but if B gets dropped above A the correct index would be 2,1,3)
Nothing in my code is custom: I just include knockout-sortable and it's plug and play. I usually always include a code snippet, but I don't feel that's useful. The only thing I know is that I'm probably gonna need a ko.computed(), but I have no idea what to fill it in with.
If you look at example http://jsfiddle.net/rniemeyer/Jr2rE/, you can see that the plug-in works by updating an observable array of data. Because of this, you don't have to keep track of the index value. The order of the records, technically, gives you all the information you need.
That being said, I ran into the same issue in last year. To solve my problem, I added a consecutively numbered index property to each object in my observable array. Then, when the sortable plug-in re-arranged the contents of the observable array, I just had to read out the new index property to know the sort order.

How do I compare Application.windows[x] to Application.activeWindow?

I'm creating a Firefox extension, in which I want to iterate through the Application.windows array and check if one of its elements is the same as Application.activeWindow.
The mentioned excerpt from my code looks like this:
for (var i in Application.windows) {
if (Application.windows[i]==Application.activeWindow) alert('debug');
// there was some more complex code than alert('debug'),
// but since it didn't work, I decided to try with an alert
}
Unfortunately, the 'debug' alert is never viewed. Thus I decided to try this code (with only one window opened):
// the following code runs in an event listener for window.onload
alert(Application.windows[0]);
alert(Application.activeWindow);
alert(Application.windows[0]==Application.activeWindow);
Firefox displayed 3 alerts: the first one was [object Object], the second one - [xpconnect wrapped fuelIWindow], and the last one (which didn't surprise me) said false. So it seems the objects I'm trying to compare have different types. How can I deal with this? Thanks in advance.
You have two problems.
The first is that XPConnect doesn't support array-valued properties, so when FUEL (or STEEL or SMILE) return an array, they're actually returning an nsIVariant of internal objects! On the other hand, single-valued objects return an XPConnect wrapper which hides the internal object.
The second is that each time you access windows or activeWindow, new internal objects are created, so even two calls to activeWindow return different objects.
The way around this is to avoid FUEL and enumerate the windows directly using the window mediator.

Categories

Resources