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

Length of array with indexes that are not consecutive integers

本文关键字:数组 整数 连续 索引      更新时间:2023-09-26

刚刚意识到JavaScript的原生.length属性通过在数组的最后一个数字索引上添加1来工作…谁有一个很好的解决方案,以获得实际的元素长度与索引不连续的数组?

//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>

您可以使用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"]

您可以使用Array#reduce和计数。

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

使用 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);
<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>