Find length (size) of an array in JavaScript
I think I'm going crazy. I have a simply question that I'm struggling with for some reason.
Why does the below return 'undefined'?
var testvar={};
testvar[1]=2;
testvar[2]=3;
alert(testvar.length);
edit I originally typed testvar[1].length. I knew this to be an error. I meant testvar.length
Solution 1:
Because 2
isn't an array, it's a number. Numbers have no length.
Perhaps you meant to write testvar.length
; this is also undefined, since objects (created using the { ... }
notation) do not have a length.
Only arrays have a length property:
var testvar = [ ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length); // 3
Note that Javascript arrays are indexed starting at 0
and are not necessarily sparse (hence why the result is 3 and not 2 -- see this answer for an explanation of when the array will be sparse and when it won't).
Solution 2:
testvar[1] is the value of that array index, which is the number 2. Numbers don't have a length property, and you're checking for 2.length which is undefined. If you want the length of the array just check testvar.length
Solution 3:
Integer has no method length. Try string
var testvar={};
testvar[1]="2";
alert(testvar[1].length);