计算数组中的空值 [英] count empty values in array

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

问题描述

给出一个数组:

var arr = [1,,2,5,6,,4,5,6,,];

计算有多少个值:(长度-删除空值后的长度)

Count how many empty values is has: (length - length after removing the empty values)

var empties = arr.length - arr.filter(function(x){ return true }).length;

// return 3

或类似的东西

arr.empties = arr.length;
arr.forEach(function(x){ arr.empties--  });

// arr.empties returns 3

这是最好的方法还是我错过了什么?

Is this the best way or am I missing something?

推荐答案

根据您对另一个答案的评论,您似乎在追求最短的方法.好吧,您可能需要考虑自己的示例的变体:

Based on your comments to another answer, it looks like you're after the shortest method. Well, you might want to consider a variation of your own example:

var empties = arr.length - arr.filter(String).length;

您要做的只是传递一个本机函数而不是一个匿名函数,从而节省了一些宝贵的字节.只要不返回布尔值,任何本机构造函数或函数都可以.

All you're doing is passing a native function rather than an anonymous function, saving a few precious bytes. Any native constructor or function will do, as long as it doesn't return a boolean.

您需要更加具体地考虑最佳方式".例如,某些方法将提供比其他方法更好的性能,某些方法更简洁,某些方法具有更好的兼容性.

You need to be more specific about what you would consider the 'best way'. For instance, some methods will give better performance than others, some are more concise and some have better compatibility.

您在文章中提到的解决方案要求浏览器与ECMAScript 5th Edition规范兼容,因此它们不能在某些旧版浏览器中使用(阅读:IE8及更低版本).

The solutions you mention in the post require browsers to be compatible with the ECMAScript 5th Edition specification, so they won't work in some older browsers (read: IE8 and lower).

最佳"的全方位方法是一个简单的循环.它不像您的方法那样简洁,但无疑将是最快,最兼容的方法:

The "best" all-round approach is a simple loop. It's not as concise as your methods, but it will no doubt be the fastest and most compatible:

var arr = [1,,2,5,6,,4,5,6,,], count = 0, i = arr.length;

while (i--) {
    if (typeof arr[i] === "undefined")
        count++;
}

这利用了循环优化(使用 while 且递减速度快于 for ).

This makes use of loop optimisations (using while and decrementing is faster than for).

另一种方法是对数组进行排序,以使 undefined 项都位于末尾,并使用循环向后迭代:

Another approach would be to sort the array so that undefined items are all at the end and use a loop to iterate backwards:

var arr = [1,,2,5,6,,4,5,6,,], count = 0;
arr.sort();
while (typeof arr.pop() === "undefined") count++;

alert(count); 
//-> 3

此方法将修改原始数组并删除那些可能不是您想要的项目.但是,在非常大的阵列上,可能要快得多.

This approach would modify the original array and remove those items which may not be what you want. However, it may be much faster on very large arrays.

性能测试套件
http://jsperf.com/count-undefined-array-elements

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

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