编辑:这已被错误地标记为重复数据删除技术(见注释讨论)解决这一特定问题是由文章作者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