计算数组中的空值

编程入门 行业动态 更新时间:2024-10-21 07:45:39
本文介绍了计算数组中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出一个数组:

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.

性能测试套件 jsperf/count-undefined-array-elements

更多推荐

计算数组中的空值

本文发布于:2023-11-22 13:49:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!