Have you ever noticed how JavaScript's .length
property calculates the length of an array by adding one to the last numerical index? Do you know a solution for accurately determining the element length of arrays with non-consecutive indexes?
//Perfectly works with consecutively indexed array length!
var test_array = [4,5,6,7,8];
$('#indexed-array').html("Consecutively Indexed Array Length: " + test_array.length);
//Trouble arises with unconsecutively indexed arrays!
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>