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

84
Views
devolución de llamada de filtro de matriz javascript con thisArg no funciona

De acuerdo con The Docs , el siguiente es un uso válido de filter con una devolución de llamada Y un argumento: filter(callbackFn, thisArg) Donde 'thisArg' reemplaza a 'this' en el contexto de la devolución de llamada. Sin embargo, este no parece ser el caso, o no puedo conseguir que sea el caso.

En este ejemplo simple, debería poder filtrar la matriz en función de las etiquetas. Si codifico un valor dentro de la devolución de llamada, funciona, pero al proporcionar una etiqueta a través de 'thisArg', no se devuelve nada y this.tag no está definido.

¿Pensamientos?

 musics = [ { name: 'stinks like unwashed adolescent', tags: ['teen', 'energetic', 'excelent'] }, { name: 'After beethovens 4th', tags: ['older', 'moving', 'excelent'] }, { name: 'wap', tags: ['hip-hop', 'pounding', 'excelent'] } ] const filterTags = (element, index, arr) => { console.log(this.tag) return element.tags.includes(this.tag) } console.log(musics.filter(filterTags, {tag:'teen'}))

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

0

No puede usar una función de flecha aquí ya que las funciones de flecha heredan su this -context del ámbito adjunto .

Prueba esto:

 const musics = [ { name: 'stinks like unwashed adolescent', tags: ['teen', 'energetic', 'excelent'] }, { name: 'After beethovens 4th', tags: ['older', 'moving', 'excelent'] }, { name: 'wap', tags: ['hip-hop', 'pounding', 'excelent'] } ] const filterTags = function(element, index, arr) { console.log(this.tag) return element.tags.includes(this.tag) } console.log(musics.filter(filterTags, {tag:'teen'}))

Un enfoque funcional utilizando un cierre:

 const musics = [ { name: 'stinks like unwashed adolescent', tags: ['teen', 'energetic', 'excelent'] }, { name: 'After beethovens 4th', tags: ['older', 'moving', 'excelent'] }, { name: 'wap', tags: ['hip-hop', 'pounding', 'excelent'] } ] const hasTag = tag => element => element.tags.includes(tag) console.log(musics.filter(hasTag('teen')))

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!