Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 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 Answer

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 } ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...