“已定义”的计数数组元素 [英] Count of "Defined" Array Elements

查看:160
本文介绍了“已定义”的计数数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数组:

var arr = [undefined, undefined, 2, 5, undefined, undefined];

我想得到 定义的元素数量(即:那些 undefined )。除了遍历数组之外,还有一个很好的方法吗?

I'd like to get the count of elements which are defined (i.e.: those which are not undefined). Other than looping through the array, is there a good way to do this?

推荐答案

在最近的浏览器中,你可以使用过滤器

In recent browser, you can use filter

var size = arr.filter(function(value) { return value !== undefined }).length;

console.log(size);

另一种方法,如果浏览器支持 indexOf

Another method, if the browser supports indexOf for arrays:

var size = arr.slice(0).sort().indexOf(undefined);

如果对于荒谬,你在数组中只有一位数的元素,你可以使用那个肮脏的技巧:

If for absurd you have one-digit-only elements in the array, you could use that dirty trick:

console.log(arr.join("").length);

您可以使用多种方法,但最后我们必须看看它是否真的值得做这些而不是循环。

There are several methods you can use, but at the end we have to see if it's really worthy doing these instead of a loop.

这篇关于“已定义”的计数数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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