1

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?
3
  • 2
    new Array(2) means create an array of length 2. Why do you expect 1? Commented Jun 11, 2013 at 7:01
  • seems legit, what's the issue? Commented Jun 11, 2013 at 7:01
  • javascript arrays are 0 based, so if you define an Array(2) that means an array with a length of 2 and a max index of 1 (starting at 0) Commented Jun 11, 2013 at 7:02

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.