获取对象的长度 [英] Getting length of an object
本文介绍了获取对象的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下对象:
var l={"a":1,"b":2,"c":5};
我想得到这个的长度
alert(l.length);
但返回 undefined
。显然,我希望得到 3
作为答案。
but that returns undefined
. Obviously I'm looking to get 3
as the answer.
推荐答案
您可以使用 Object.keys()
,它返回对象中键的数组:
You can count the number of entries in an object using Object.keys()
, which returns an array of the keys in the object:
var l = {a: 1, b: 2, c: 3};
Object.keys(l).length;
但是,实现自己的属性可能更有效(和跨浏览器):
However, it might be more efficient (and cross browser) to implement your own property:
Object.length = function(obj) {
var i = 0;
for(var key in obj) i++;
return i;
}
Object.length(l);
请注意,虽然我可以将函数定义为 Object.prototype.length
,允许你写 l.length()
,我没有,因为如果对象容器的密钥<$ c $,那会失败C>长度。
Note that although I could have defined the function as Object.prototype.length
, allowing you to write l.length()
, I didn't, because that would fail if your object container the key length
.
这篇关于获取对象的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文