Estoy aprendiendo sobre filter() y lo que hace este método. Hasta ahora entendí lo que hace y cómo usarlo. La parte con la que estoy luchando es tratar de comprender todos sus parámetros opcionales y lo que hacen. Entiendo cómo usar todos sus parámetros requeridos (callbackFunction, currentValue) pero no los opcionales (index,arr,thisValue).
sintaxis: array.filter(callbackFunction(currentValue, index, arr), thisValue)
Me gustaría saber el código detrás del método filter(). Hice uno usando los parámetros requeridos (callbackFunction, currentValue), pero no pude averiguar cómo incorporar el índice, arr y thisValue en mi código. Si puede ayudarme a hacer eso para que pueda ver qué sucede dentro del método filter() y qué le está haciendo a los parámetros index,arr y thisValue, ¡me ayudará muchísimo!
Aquí está mi código hasta ahora:
// The global variable const s = [23, 65, 98, 5]; Array.prototype.myFilter = function(callback) { const newArray = []; for (let i =0; i < this.length; i++){ let currentElement = this[i] let check = callback(currentElement); //if true (item is odd) then it pass the filter and can be included in new array if (check){ newArray.push(currentElement); } } return newArray; }; const new_s = s.myFilter(function(item) { return item % 2 === 1; //if true (item is odd) then it pass the filter and can be included in new array }); console.log(new_s) //[23, 65, 5]Simplemente vincúlelos a callback callback(currentElement, i, this) , s.myFilter(function(item, index, arr) así:
// The global variable const s = [23, 65, 98, 5]; Array.prototype.myFilter = function(callback) { const newArray = []; for (let i =0; i < this.length; i++){ let currentElement = this[i] let check = callback(currentElement, i, this); //if true (item is odd) then it pass the filter and can be included in new array if (check){ newArray.push(currentElement); } } return newArray; }; const new_s = s.myFilter(function(item, index, arr) { console.log("index", index); console.log("arr", arr); return item % 2 === 1; //if true (item is odd) then it pass the filter and can be included in new array }); console.log(new_s) //[23, 65, 5]Ya está pasando el currentValue a la devolución de llamada, pero parece que le faltan los parámetros index y arr .
let check = callback(currentElement, i, this); El segundo parámetro para el filter es el contexto this para la función de devolución de llamada. Simplemente agregue eso a la definición de la función.
Array.prototype.myFilter = function(callback, thisContext) { y devolver la callback con el thisContext dado:
let check = callback.call(thisContext, currentElement, i, this);