gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:07:49 24 4
gpt4 key购买 nike

刚刚意识到 JavaScript 的 native .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>

最佳答案

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

关于javascript - 索引不是连续整数的数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com