稀疏数组的长度 [英] Length of sparse arrays

查看:58
本文介绍了稀疏数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组将取n个值,但这些值将在不同的时间添加到不同的索引。但是,我需要在特定时间的数组长度。

I'm having an array will take n values, but the values will be added to different index at different time. But, I need the length of the array at a particular time.

案例1

var a = [1,2,3,3,4]

a.length //Returns 5 - OK

案例2

var a =[]
a[20] = 2
a.length //Returns 21 but I would like it to return 1

如何为案例2 获取 1 的长度?

推荐答案

如果你可以使用下划线 lodash 。您可以尝试这样

If you can use underscore or lodash. You may try like this

var arrLen = _.compact(youArr).length;

如果你想使用纯JS ..你需要编写简单的函数。这将计算元素数量不等于false。

If you want to use pure JS..you will need to write simple function. That will count number of elements not equal to false.

var len = 0;
arr.forEach(function(el){
  if (el) {count++;}
});
console.log(len);

正如@vlaz提到 .reduce 也可以。

As @vlaz mention .reduce will also work.

对于数字我会使用 Number.isInteger 取而代之的是数字计数 typeof value!==undefined as as。

For numbers I would use Number.isInteger to get number count instead typeof value !== "undefined" as so on.

你可以省略parseInt方法,如果你确定数组中的值总是整数类型。

You can omit parseInt method, if you sure that values in array will always be integer type.

所以在下面的示例中,parseInt = 4,没有= 3

So in example below with parseInt = 4, without = 3

var arr = [];

arr[7] = 1;
arr[17] = null
arr[33] = 0;
arr[66] = undefined;
arr[77] = '7';
arr[99] = -7;
arr[9001] = false;


var count = arr.reduce((x, v) => Number.isInteger(parseInt(v)) ? x+1 : x, 0);

console.log(count);

希望这会有所帮助。

这篇关于稀疏数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆