I've run into a rather interesting problem. The code below generates an array that, when logged, gives the value [undefined × 1]
. According to this answer, that means that the array has unitialized indexes--in this case, only one. However, since I'm only using array.push()
to avoid exactly this sort of problem, I'm kind of lost. To the best of my knowledge only assigning an index at least one index greater than other initialized indexes could cause the problem. Anyhow, here's the code:
function Thing(params) {
var that = this;
this.OtherObject = function OtherObject(param) {
this.param = param;
}
this.Foo = function Foo() {
this.bar = [];
this.add = function(item) {
if (this.bar.length != 0) {
for (var i = 0, len = this.bar.length; i < len; i++) {
if (this.bar[i].param <= item.param) {
this.bar.splice(i, 0, item);
}
}
} else {
this.bar[0] = item;
console.log(this.bar);
}
}
this.pop = function() {
return this.bar.pop();
}
this.length = function() {
return this.bar.length;
}
}
this.someFunc = function() {
var myThing = new that.Foo();
myThing.add(new that.OtherObject(3));
while (myThing.length() > 0) {
var someVar = myThing.pop();
}
}
}
var myThing = new Thing({
myParam: "someValue"
});
myThing.someFunc();
I created a test case to see if I could narrow the problem down, but I ended up re-typing 95% of my code until I ran into the issue again, which appears to be related with my use of myThing.pop()
. You can find a fiddle here which demonstrates the issue in question.
So... any ideas as to what could be causing this? Is this actually a problem with the way I've nested my objects? (which I did following a pattern given to me in this answer to a previous question of mine).
In case you're wondering what I could possibly be trying to do here, I'm treating the outside object like a sort of namespace, which I'm doing to avoid cluttering up the global namespace (this will eventually be a pathfinding library, if I get my act together here). The Foo
object is meant to be a sort of ordered list such that I can get the closest node (the one with the lowest param
property) by pop()
ing the stack.