user991554
user991554

Reputation: 173

unable to get array length of object property in javascript

defined a simple javascript object and assigned array to one property but not able to get the length of the array. returning 2 rather than 1 for below code.

//activity object
var activity={
    timer:0,
    questions_completed:new Array(2),
    knifes:0,
    getTimer:function(){
        return timer; 
    } 
};

alert(activity.questions_completed.length); //getting 2?

Upvotes: 1

Views: 696

Answers (2)

user1823761
user1823761

Reputation:

new Array with a single parameters passed to it as number, will create an array with specific length:

var arr = new Array(2);

arr;
// -> [undefined, undefined]

arr.length;
// -> 2

Instead use [] notation:

var arr = [2];

arr;
// -> [2]

arr.length;
// -> 1

var activity = {
    timer:0,
    questions_completed: [2],
    knifes:0,
    getTimer:function(){
        return timer; 
    } 
};

alert(activity.questions_completed.length);
// 1

Upvotes: 6

powercoder23
powercoder23

Reputation: 1404

The below line defines the length of your array which is 2, however you have not pushed any item in your array the length will show 2, which is absolutely correct..!

questions_completed:new Array(2)

Upvotes: 0

Related Questions