JavaScript对象的长度(即关联数组) [英] Length of a JavaScript object (that is, associative array)
问题描述
如果我有一个JavaScript关联数组,说:
If I have a JavaScript associative array, say:
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
有一个内置的或公认的最佳实践方法获取此数组的长度?
Is there a built-in or accepted best practice way to get the length of this array?
JavaScript没有关联数组 - 它只有对象的其可以用作关联数组的概念的**
JavaScript does not have associative arrays -- it only has objects, which can be used as a notion of associative arrays.**
推荐答案
最强劲的答案(即捕获的你试图同时引起的错误最少要做什么的意图)将是:
The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myArray);
有在JavaScript的一种习惯,你不添加东西到的Object.prototype 的,因为它可以打破在各个库枚举。添加方法对象通常是安全的,但。
There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
下面是一个更新为2016年和wides ES5的$ P $垫的部署和超越。对于IE9 +和所有其他现代ES5 +功能的浏览器,你可以使用 Object.keys ()
因此,上述code只是变成了:
Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys()
so the above code just becomes:
var size = Object.keys(myObj).length;
这并不需要修改,因为 Object.keys任何现有的原型()
现在是内置的。
This doesn't have to modify any existing prototype since Object.keys()
is now built in.
这篇关于JavaScript对象的长度(即关联数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!