I’m unable to get the length of the following JSON array object. Actually I need to return the values of the penultimate array elements.
var myObject = { "Maths" : [{"Name" : "Amit", "Marks" : 67, "age" : 23 },
{"Name" : "Sandeep", "Marks" : 65, "age" : 21 },
{"Name" : "Shali", "Marks" : 56, "age" : 27 },
{"Name" : "Santosh", "Marks" : 78, "age" : 41 }] }
a = myObject.Maths.length - 1;
alert(a);
var b=new Object();
b.mk=myObject.Maths[a]['Marks'];
b.ag=myObject.Maths[a]['age'];
alert(b.mk);
alert(b.ag);
Why is this returning 78 and 41 when it should return 56 and 27?
Why do you think it would return 56 and 27? Do you realize array indexes start at 0?
So if a = 3 (length – 1, 4 – 1 = 3).
the third index of the Math’s array is exactly what you are seeing in the output.
edit: so, in order to get the penultimate, your index would need to be length – 2. (of course making sure you array is actually long enough to not run into an out of bounds error)