Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
¿Cómo verificar la cantidad de argumentos proporcionados a una devolución de llamada?

Estoy tratando de implementar mi versión de forEach para asegurarme de que lo entiendo correctamente, sin embargo, dado que la devolución de llamada proporcionada a forEach puede aceptar 1, 2 o 3 argumentos, necesito encontrar una manera de verificar la cantidad de argumentos.

Por ejemplo, esto es lo que tengo actualmente:

 Array.prototype.myForEach = (callback) => { //console.log(callback.arguments.length, "arguments supplied to callback") This doesn't work. //Check the number of arguments provided to the callback if(typeof callback === 'function') { for(var i = 0; i < this.length; i++) { //If single argument then callback(this[i]) should be invoked. callback(this[i], i, this) } } else throw new Error("Callback for myForEach is not a function") }

Lo que pretendo lograr es:

arr.myForEach((a, b) => {} //a should refer to element, b to the index, c to the array

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Si bien puede verificar la cantidad de argumentos proporcionados al verificar la propiedad .length de la función:

 Array.prototype.myForEach = (callback) => { console.log(callback.length); }; [].myForEach((arg1, arg2) => {}); [].myForEach((arg1) => {});

No es necesario aquí: no hay problema con pasar todos los argumentos independientemente de que la devolución de llamada los use o no (y si la devolución de llamada acepta más de 3 argumentos, por alguna extraña razón, no estarán undefined dentro de la devolución de llamada, al igual que con forEach ) .

 Array.prototype.myForEach = function(callback) { if (typeof callback !== 'function') { throw new Error("Callback for myForEach is not a function") } for(var i = 0; i < this.length; i++) { callback(this[i], i, this); } }; ['a', 'b'].myForEach((item, i, arr) => { console.log(item); console.log(i); console.log(arr); });

about 4 years ago · Juan Pablo Isaza Report

0

El número de argumentos pasados se reflejará en callback.length

 Array.prototype.myForEach = (callback) => { console.log(callback.length); } const arr = [1,1]; arr.myForEach((arg1, arg2, arg3) => {}); //3 arr.myForEach((arg1, arg2, arg3, arg4) => {}); //4 arr.myForEach((arg1, arg2, arg3, arg4, arg5) => {}); //5

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!