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.
myArray[y.recents.length - 1]
exists and is not undefined
- 0x499602D2 2012-04-03 23:59
myArray[y.recents.length-1]
is undefined, and undefined.time
fails - Niko 2012-04-04 00:06
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
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.