javascript thisArg 不工作的数组过滤器回调

javascript array filter callback with thisArg not working

根据 The Docs,以下是带回调和参数的过滤器的有效用法: 过滤器(callbackFn,thisArg) 其中 'thisArg' 在回调上下文中替换 'this'。但是,好像不是这样,或者我无法理解。

在这个简单的示例中,我应该能够根据标签过滤数组。如果我在回调中硬编码一个值,它可以工作,但通过 'thisArg' 提供标记不会返回任何内容,并且 this.tag 未定义。

想法?

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

您不能在此处使用箭头函数,因为 arrow functions inherit their this-context from the enclosing scope

试试这个:

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

使用闭包的函数式方法:

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')))