数组方法:filter妙用

fliter()方法返回的数组元素是调用的数组的一个子集。传递的函数是用来逻辑判定的,该函数返回true或false。调用判定函数就像调用forEach()和map()一样。

如果返回值为true或能转化为true的值,那么传递给判定函数的元素就是这个子集的成员,它将被添加到一个作为返回值的数组中。例如:

a=[5,4,3,2,1];
smallvalues = a.filter(function(x) { return x < 3 }); // [2, 1]
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

注意,filter() 会跳过稀疏数组中缺少的元素,它的返回数组总是稠密的。为了压缩稀疏数组的空缺,代码如下:

var dense = sparse.filter(function() { return true; });


甚至,压缩空缺并删除undefined和null元素,可以这样使用filter():

a = a.filter(function(x) { return x !== undefined & x != null; });
原文地址:https://www.cnblogs.com/LeoXnote/p/13047930.html