索引不是连续整数的数组长度

时间:2016-07-01 18:39:59

标签: javascript arrays

只是意识到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>

3 个答案:

答案 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]

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用Array#reduce并计算。

var test_array = [, 1, , 2, , , , 7],
    count = test_array.reduce(r => r + 1, 0);

console.log(count);