OOO javascript: object self reference returns undefined but console shows it exists

Go To StackoverFlow.com

2

Okay, so I did search a bit before posting... no luck (or maybe I'm just stupid).

I have this array I call "myArray" and I push objects onto it to populate some variables:

myArray.push({
    time        : (y.moveTime - y.startTime),
    pos         : y.move,
    last        : myArray[y.recents.length-1].time
});

My issue is why does firebug complain about the "last" variable: "Uncaught TypeError: Cannot read property 'time' of undefined". If I do

last        : myArray[y.recents.length-1]

everything is fine.

An observation I don't understand: The array is empty when I have the ".time" reference, but if I remove it, the array is full.

What am I missing here? I don't get it :(

Thanks for any pointers.

2012-04-03 23:55
by tim
I should add that i do understand that the very first item in this array will have the "last" variable "undefined" since it's got nothing to refer back to - tim 2012-04-03 23:59
Have you checked that myArray[y.recents.length - 1] exists and is not undefined - 0x499602D2 2012-04-03 23:59
@tim You have the answer right there in your own comment: For the first item myArray[y.recents.length-1] is undefined, and undefined.time fails - Niko 2012-04-04 00:06
possible duplicate of Self-references in object literal declarationsBergi 2013-07-24 17:42


4

The error means that the evaluated value of

myArray[y.recents.length-1]

is not an object that has a time property. This likely occurs when you perform the first push because the array does not yet have any elements.

If you want to hide the error and just assign the last property to undefined in this case, you can just add a fallback value:

last: (myArray[y.recents.length - 1] || {}).time 
2012-04-04 00:02
by Peter Olson
Thanks for the clarification, Peter, I get it now - tim 2012-04-18 17:27


0

The value of myArray[y.recents.length-1] can be anything (some string, object, array, null etc.). you can set the value of last with it and will not make any error.

however, if you set a property to a non-object (like setting time), it will cause an error.

2012-04-04 00:02
by Joseph