在Javascript中查找数组长度 [英] Find Array length in Javascript
问题描述
这听起来很愚蠢。我们怎样才能在JavaScript中找到数组的确切长度;更确切地说,我想找到阵列中占据的总位置。
This will sound a very silly question. How can we find the exact length of array in JavaScript; more precisely i want to find the total positions occupied in the array.
我有一个简单的场景,我猜大多数人可能都知道。
I have a simple scenario which i guess most of you might be aware of.
var a = [1,2,3];
a.length; //This will output 3
现在,如果我给出
a[100] = 100;
a.length; // The output is 101;
我想得到数组的确切大小,在上面的情况下应该是4。
I want to get the exact size of the array which in the above case should be 4.
推荐答案
这将为您提供数组中真正存在的元素数量:
This will give you the number of elements really present in your array:
Object.keys(a).length
编辑
正如JLRishe的评论所指出的, Object.keys(a)。length 返回对象a中存在的键数。
如果我添加这样的密钥:
As pointed in comments by JLRishe, Object.keys(a).length returns the number of keys present in the object a. If I add a key like that:
a= [1,2,3];
a['key']= "akey";
然后
Object.keys(a).length 将返回4
但是key不是数组的一部分,它是数组Object的属性,
console.log(a) 给你[1,2,3]。
but "key" is not a part of the array, it's a property of the array Object, console.log(a) gives you [1,2,3].
因此,要获得数组中元素数量的更可靠值,我们只需要计算正整数键值:
So, to have a more reliable value of the number of elements in an array, we need to count only positive integer key values:
Object.keys(a).filter(function(el){return !(+el % 1) && +el>=0 && +el < Math.pow(2,32) ;}).length
Object.keys返回一个String数组。使用 a ['1']
或 a [1]
在数组中赋值是等效的。
数组索引键也必须小于2 ^ 32。
Object.keys returns an array of String. Assigning a value in an array with a['1']
or a[1]
is equivalent.
Array index keys have also to be less than 2^32.
这篇关于在Javascript中查找数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!