当前位置: 首页 > Web前端 > HTML5

js数组中filter、map、reduce、find等方法的原理

时间:2023-04-05 00:15:21 HTML5

filter的用法及原理实现filter过滤,filter()使用指定的函数对所有元素进行测试,并创建一个包含所有通过的元素的新数组考试。用法letarr=[2,4,6,8];letarr1=arr.filter(function(item){returnitem>5})console.log(arr1)//[6,8]letarr=[{id:1,name:"Alex",age:18},{id:2,name:"Teamo",age:15},{id:3,name:"Lily",age:16},{id:4,name:"Lucy",age:17},{id:5,name:"Tom",age:19}]letarr1=arr.filter(function(item){returnitem.age>15})console.log(arr1)//[{id:1,name:"Alex",age:18},{id:3,name:"Lily",age:16},{id:4,name:"Lucy",age:17},{id:5,name:"Tom",age:19}]原理实现Array.prototype.filter1=function(fn){if(typeoffn!=="function"){thrownewTypeError(`${fn}不是函数`);}让newArr=[];for(leti=0;i5})console.log(arr1)//[6,8]之后读书,有那么容易吗?其他实现类似。推荐手写map的用法和原理,实现map映射。map()方法返回一个新的数组,数组中的元素为原数组元素。调用函数处理后的值。用法letarr=['bob','grex','tom'];letarr1=arr.map(function(item){return`

  • ${item}
  • `;});console.日志(arr1);//['
  • bob
  • ','
  • grex
  • ','
  • tom
  • ']原理实现Array.prototype.map=function(fn){if(typeoffn!=="function"){thrownewTypeError(`${fn}不是函数`);}让newArr=[];for(leti=0;i=2});console.log(arr5);//2find原理实现Array.prototype.find=function(fn){if(typeoffn!=="function"){thrownewTypeError(`${fn}isnotafunction`);}for(leti=0;i5});控制台日志(标志);//truesome实现Array.prototype.some=function(fn){if(typeoffn!=="function"){thrownewTypeError(`${fn}isnotafunction`);}for(leti=0;i5});控制台日志(标志);//false原理实现Array.prototype.every=function(fn){if(typeoffn!=="function"){thrownewTypeError(`${fn}isnotafunction`);}for(leti=0;i