灵感来自this article ,我一直在重构一些旧代码。
但是,由于 Array.prototype.filter(callback, thisArg)
的第二个参数绑定(bind),我在使用 Array.prototype.filter 传递参数时遇到了问题回调中的 this
对象,但箭头函数不绑定(bind) this
。
在我的示例中,我使用 Object.keys()
从关联数组中获取键(是的,我知道,技术上在 JavaScript 中不可用),然后通过属性过滤该数组他们的对象在关联数组 this[item].property
中,但由于此绑定(bind)不可用,所以失败。
那么,使用箭头函数,如何将参数传递给 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);
最佳答案
您可以使用Object.entries
。它提供了键和值,因此您不需要对对象本身的引用:
const arr = {
a: {
property: true,
otherProp: false
},
b: {
property: true,
otherProp: false
},
c: {
property: false, // to be excluded
otherProp: true
},
},
hasProperty = ([key, value]) => value.property,
first = ([key]) => key,
getMatchingKeys = object => Object.entries(object).filter(hasProperty).map(first);
console.log(getMatchingKeys(arr));
.as-console-wrapper { max-height: 100% !important; top: 0; }
您还可以使用bind
——不是绑定(bind)this
,而是绑定(bind)第一个参数:
const arr = {
a: {
property: true,
otherProp: false
},
b: {
property: true,
otherProp: false
},
c: {
property: false, // to be excluded
otherProp: true
},
},
hasProperty = (object, key) => object[key].property,
getMatchingKeys = object => Object.keys(object).filter(hasProperty.bind(null, arr));
console.log(getMatchingKeys(arr));
.as-console-wrapper { max-height: 100% !important; top: 0; }
另请参阅 my answer to another question 中的一些其他选项.
关于javascript - 带有箭头函数回调的 Array.prototype.filter() 参数? (没有这个绑定(bind)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45990425/