Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - ES6 how to get source code for filter( ) method

I've tried to reproduce the method filter so far I have got:

function filtre(...[T,x,y]){
let tabPersF = [];
for (let pers of T) {
    if (x(...[pers,y])) {
      tabPersF.push( pers ); 
     }

}
  return tabPersF;
}

How about it?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I've tried to reproduce the method filter I got this and I know it's not good.

Multiple issues with this code

  • array2 not initialized
  • array2 not an array and what is puts
  • function keyword as parameter

Make it

function filter(array, func) {
  let array2 = [];
  for ( var counter = 0; counter < array.length; counter++) {       
    if (func(array[counter], counter, array )) {
      array2.push(array[counter]);
    }
  }
  return array2;
}

console.log( filter( [1,2,3], function(s){ return s>1 } ) );

console.log( filter( ["132","322","23433"], function(s){ return s.length>3 } ) );

var arr = [ {name: "asdasd", age: 10}, {name: "asdasd2", age: 20} ];

console.log( filter( arr , function(s){ return s.age>19 } ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...