【问题标题】:javascript array filter callback with thisArg not working带有thisArg的javascript数组过滤器回调不起作用
【发布时间】:2021-12-18 00:29:41
【问题描述】:

根据The Docs,以下是带有回调和参数的过滤器的有效用法: 过滤器(回调Fn,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'}))

【问题讨论】:

    标签: javascript arrays filter callback arguments


    【解决方案1】:

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

    【讨论】:

    • 这是正确答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2015-08-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多