Reputation: 173
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
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
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