Ed.
Ed.

Reputation: 4577

Find length (size) of an array in JavaScript

I have a simple 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

Upvotes: 67

Views: 345112

Answers (7)

RafaSashi
RafaSashi

Reputation: 17205

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

Upvotes: 0

Tanmaya
Tanmaya

Reputation: 1

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

Upvotes: -2

kush
kush

Reputation: 645

       var mode = [];
                $("input[name='mode[]']:checked").each(function(i) {
                    mode.push($(this).val());
                })
 if(mode.length == 0)
                {
                   alert('Please select mode!')
                };

Upvotes: -2

Tanmaya
Tanmaya

Reputation: 1

var array=[];

array.push(array);  //insert the array value using push methods.

for (var i = 0; i < array.length; i++) {    
    nameList += "" + array[i] + "";          //display the array value.                                                             
}

$("id/class").html(array.length);   //find the array length.

Upvotes: -3

Cameron
Cameron

Reputation: 98746

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

Upvotes: 118

mVChr
mVChr

Reputation: 50185

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

Upvotes: 5

Dim_K
Dim_K

Reputation: 571

Integer has no method length. Try string

var testvar={};
testvar[1]="2";
alert(testvar[1].length);

Upvotes: 3

Related Questions