1

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?

2
  • 3
    Arrays are 0 based. The penultimate would be .length - 2.
    – user1106925
    Apr 11, 2012 at 2:25
  • I'm still thinking why I didn't notice that! Thanks!
    – ZzzZZz
    Apr 11, 2012 at 2:29

1 Answer 1

3

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)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.