Getting the length of a 'named' array?
This question already has an answer here:
You could use Object.keys()
to obtain an array of keys, then count them:
Object.keys(array).length
Or, if you're targeting ECMAScript 3 or otherwise don't have Object.keys()
, then you can count the keys manually:
var length = 0;
for (var key in array) {
if (array.hasOwnProperty(key)) {
++length;
}
}
There are a few edge cases with this approach though, depending on the browsers you're targeting, so using Mozilla's polyfill for Object.keys()
instead might be a good idea.
上一篇: 单击JavaScript数组长度
下一篇: 获取'命名'数组的长度?