Reputation: 55
Trying to get the length of a variable territories
, yet when I do territories.length
it gives me 0
. When I use console.log
and look in the JavaScript console, it shows
child
{
length: 0,
models: Array[0],
_byId: Object,
_events: Object,
_listenerId: "l11"
}
So the length is 0
but when I expand that, it says that the length is9
. I want it to be 9
. How can I get length:9
?
Upvotes: 0
Views: 2425
Reputation: 1224
Length is the right property, but it depends on what kind of variable territories is. The below code for a string example outputs 9.
var territories = "my string";
var length = territories.length;
alert(length);
Since in this case territories is actually a backbone collection, you can find more information about this issue from the following question: Get collection length
Unfortunately you can't save the fetched collection data because the fetch function in backbone is asynchronous. You need to use a callback function to do whatever you need done with the length property. For more information see How to return value from an asynchronous callback function? and http://recurial.com/programming/understanding-callback-functions-in-javascript/
Upvotes: 0
Reputation: 7416
You can do this to get the number of properties in any javascript object, at least in modern browsers:
Object.keys(myObj).length;
You could also do this manually, like this
Object.prototype.length=function(){
var count=0;
for(var i in this){
if(this.hasOwnProperty(i)){
count++;
}
}
return count;
}
Upvotes: 1