索引不是连续整数的数组长度
Length of array with indexes that are not consecutive integers
刚刚意识到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>
相关文章:
- Js char数组将字符串整数视为整数
- 如何在JavaScript中剥离数组元素中的非整数
- 如何删除“;整数“;JavaScript中对象的数组
- 效率:整数数组的一个子集中两个项之间的最大差值
- 在JS中返回数组的大整数运算
- 创建一个javascript数组(N),该数组由连续的较小整数组成,其和为1000
- 包含整数(秒)和 setTimeout() 的数组
- 在参数数组中传递整数数组
- 将整数数组从插件传递到JavaScript
- Javascript-如何快速构建不同正整数数组的二进制表示
- 将随机整数分配给数组中的项,summa应该是一个固定的数字
- 在JavaScript中,是否使用数组's的length属性生成整数数学
- 函数来检查给定整数数组中给定位置的元素是否大于其两个邻域
- 如何将整数数组转换为人力车的 x/y 坐标
- parseInt() 不会将数组的每个数组元素转换为整数
- 角度 - 数组从承诺更新,整数不更新
- 如何用整数“平滑”数组
- 用于从包含最大求和的整数数组中提取子数组的算法
- 在 JQuery 中将整数数组转换为字符串数组
- 在angular中使用json数组整数