本文介绍了得到嵌套数组非空元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有十个阵列,空值

  onTable [0-10]。

  [Jean5,Jean3,Paul2,Jean6,,Paul4,让,peirre4,]
[Paul5,peirre6,peirre3,,Jean4,保,peirre5,Jean2,]
...

我希望得到每个数组的长度,不为空值,没有创造10个变量进行检查。

我有测试此解决方案
在阵列 ,但不是我想要的。

如果可能的话,我想这个样子

  onTable [0]。长度(不包括())

有什么好办法的作出这样的?


解决方案

使用过滤器布尔过滤非-empty元素从它子数组,并使用长度

  onTable [0] .filter(布尔)。长度

由于空字符串是在JavaScript中falsy,它会从过滤阵列中删除。

演示:

\r
\r

VAR ARR = [\r
  [Jean5,Jean3,Paul2,Jean6,,Paul4,让,peirre4,],\r
  [Paul5,peirre6,peirre3,,Jean4,保,peirre5,Jean2,]\r
];\r
\r
变种LEN =改编[1] .filter(布尔型)。长度;\r
文件撰写(LEN);

\r

\r
\r

I have ten arrays with empty value

onTable[0 to 10];

look

["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""]
["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
...

I want get length of each array without empty value and without create ten variables for check that.

I have test this solutioncount empty values in array but i dont want make ten variable. ie: count1, count2,....

I check too compare two arrays based on length: skip empty values but is not what i want.

If possible, I want this look like

onTable[0].length(exclude(""))

What is the good way for make that?

解决方案

Use filter with Boolean to filter non-empty elements from sub-array and use length on it.

onTable[0].filter(Boolean).length

As empty string is falsy in JavaScript, it'll be removed from filtered array.

Demo:

var arr = [
  ["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""],
  ["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
];

var len = arr[1].filter(Boolean).length;
document.write(len);

这篇关于得到嵌套数组非空元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 22:56