編輯:這已被錯誤地標記爲重複數據刪除技術(見註釋討論)解決這一特定問題是由文章作者here帶有箭頭函數回調的Array.prototype.filter()參數? (沒有這種綁定)
由https://hackernoon.com/rethinking-javascript-death-of-the-for-loop-c431564c84a8提供啓發我已經重構了一些舊碼。
由於Array.prototype.filter(callback,thisArg)的第二個參數在回調中綁定了「this」對象,但箭頭函數不綁定「this 」。
在我的示例中,我通過使用「Object.keys()」從關聯數組中獲取關鍵字(是的,我知道,技術上在js中不可用),然後通過其對象的屬性關聯數組「this [item] .property」,但由於此綁定不可用而失敗。
因此,擁抱箭頭函數,如何將參數傳遞給filter()中的回調函數?
const arr = {
a: {
property: true,
otherProp: false
},
b: {
property: true,
otherProp: false
},
},
hasProperty = item => this[item].property,
getMatchingKeys = object => Object.keys(object).filter(hasProperty, object);
getMatchingKeys(arr);
箭頭函數不綁定到此上自己https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – TimCodes
爲什麼它需要首先涉及'this'? '.filter(v => arr [v] .property)'已經非常可讀和簡短了。 – loganfsmyth
'hasProperty'和'getMatchingKeys'是否應該在'arr'對象字面值內? – Barmar