Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find length (size) of an array in jquery

Tags:

arrays

jquery

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

like image 347
Ed. Avatar asked Mar 15 '11 19:03

Ed.


People also ask

How do you find the length of an array?

The simplest procedural way to get the value of the length of an array is by using the sizeof operator. First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

What is array length?

Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array. Syntax: public int Length { get; } Property Value: This property returns the total number of elements in all the dimensions of the Array.

What property tells you the length of a JavaScript array?

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

How do you find the length of an array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.


2 Answers

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).

like image 130
Cameron Avatar answered Oct 15 '22 14:10

Cameron


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

like image 34
mVChr Avatar answered Oct 15 '22 14:10

mVChr