Calulating length in Javascript
This question already has an answer here:
You can do this:
Object.getOwnPropertyNames(treeObj).length; // 3
getOwnPropertyNames
returns array of properties of treeObj
whose length
can be checked.
To count the number of properties an object has, you need to loop through the properties but remember to use the hasOwnProperty function:
var count = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
count++;
}
}
If you forget to do that, you will be looping through inherited properties. If you (or some library) has assigned a function to the prototype of Object, then all objects will seem to have that property, and thus will seem one item "longer" than they intrinsically are.
consider using jQuery's each instead:
var count = 0;
$.each(obj, function(k, v) { count++; });
OR simply,
for (var p in obj)
count++;
UPDATE With current browsers:
Object.keys(someObj).length
Refer Old Post
链接地址: http://www.djcxy.com/p/27274.html上一篇: 数组和对象中的尾随逗号是规范的一部分吗?
下一篇: 在Javascript中计算长度