只是意识到JavaScript的本地.length
属性通过在数组的最后一个数字索引中添加一个来工作...任何人都有一个很好的解决方案来获取索引不连续的数组的实际元素长度?
//Consecutively Indexed Array .length works good!
var test_array = [4,5,6,7,8];
$('#indexed-array').html("Consecutively Indexed Array Length: " + test_array.length);
//Unconsecutively Indexed Array .length No BUENO!
var test_array = [];
test_array[1] = 1;
test_array[3] = 2;
test_array[7] = 3;
$('#unconsecutive-indexed-array').html("Unconsecutively Indexed Array Length: " + test_array.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="indexed-array">
</p>
<p id="unconsecutive-indexed-array">
</p>
答案 0 :(得分:2)
您可以使用Object.keys
然后获取长度
var array = [];
array[1] = 1;
array[3] = 3;
console.log(array.length); // 4
console.log(Object.keys(array).length); // 2
Object.keys
实际上用于获取对象的属性/键。
var obj = {a:'a', b:'b'};
Console.log(Object.keys(obj)); // ["a", "b"]
var arr = [1,2,3];
console.log(Object.keys(a)); //["0", "1", "2"]
答案 1 :(得分:1)
使用Array#filter
,因为它只迭代值为assigned
的数组中的那些属性(无论什么值!)
仅对已分配值的数组的索引调用
Callback
;对于已经删除或从未分配过值的indexes
,不会调用它。未通过回调测试的数组元素简单地跳过,并且在新数组中未包含。[Ref]
var test_array = [4, 5, 6, 7, 8];
$('#indexed-array').html("Consecutively Indexed Array Length: " + test_array.length);
var test_array = [];
test_array[1] = 0; //falsey values are not ignored
test_array[3] = 2;
test_array[7] = 3;
test_array[11] = undefined; //falsey values are not ignored
var filteredArray = test_array.filter(Object); //OR test_array.filter(function(){ return true; })
$('#unconsecutive-indexed-array').html("Unconsecutively Indexed Array Length: " + filteredArray.length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="indexed-array"></p>
<p id="unconsecutive-indexed-array"></p>
&#13;
答案 2 :(得分:1)
您可以使用Array#reduce
并计算。
var test_array = [, 1, , 2, , , , 7],
count = test_array.reduce(r => r + 1, 0);
console.log(count);