javascript中map和filter的区别 短命女 2022-04-13 14:15 198阅读 0赞 原生js中数组可以直接通过map(),filter()函数来进行一次操作,他们分别是做一次统一映射,和一次过滤。说的更通俗一点,就是map函数之后,数组元素个数不变,但是按照一定的条件转换,数组元素发生了变化。filter函数之后,数组元素个数可能发生了改变,但是数组元素不会发生改变。 下面通过示例说明一下这两个方法的用法。 map(function(item,index)\{ return func(item); \}); filter(function(item,index)\{ return func(item); \}): 示例中,给定一个数组,var arr = \["abc","aaa","bcd"\],通过map函数,我们将他们转大写,然后通过filter函数,将A开头的留下。 $(function(){ var arr = ["abc","aaa","bcd"]; console.log(arr); arr = arr.map(function(item,index){ console.log(item,index); return String.prototype.toUpperCase.call(item); }); console.log(arr); arr = arr.filter(function(item,index){ console.log(item,index); return String.prototype.startsWith.call(item,"A"); }); console.log(arr); }); 运行结果,如下: ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaW5pZmk_size_16_color_FFFFFF_t_70][] map,filter函数均有两个参数item,index 分别是数组元素的值和索引,我们一般对item进行转换。 另外,jQuery也提供了map,filter方法,用法和原生的map,filter类似,只不过index,item参数位置和原生正好相反。 $(function(){ var arr = ["abc","aaa","bcd"]; arr = $(arr).map(function(index,item){ console.log(index,item); return String.prototype.toUpperCase.call(item); }).filter(function(index,item){ console.log(index,item); return String.prototype.startsWith.call(item,"A"); }); console.log(arr); arr = $.makeArray(arr); console.log(arr); }); 运行结果如下: ![2018113014492039.png][] map,filter方法都会对数组所有元素进行一次转换。 [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZlaW5pZmk_size_16_color_FFFFFF_t_70]: /images/20220413/79b1dd6dec0c4f3393601bfe85d6be25.png [2018113014492039.png]: /images/20220413/bf8f1638662349f8b85753a8f2f4cca4.png
还没有评论,来说两句吧...