根據The Docs,以下是帶回呼和 arg 的過濾器的有效用法: filter(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'}))
uj5u.com熱心網友回復:
您不能在此處使用箭頭函式,因為箭頭函式this從封閉范圍 ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions )繼承它們的-context 。嘗試這個:
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'}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347358.html
標籤:javascript 数组 筛选 打回来 争论
