javascript - 带有箭头函数回调的 Array.prototype.filter() 参数? (没有这个绑定(bind))

标签 javascript arrays ecmascript-6 arrow-functions

灵感来自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/

相关文章:

javascript - 使用 React,通过单击同名按钮来加载文件的简单方法是什么?

javascript - 从嵌套的 json 值对象获取数组

javascript - Safari <select> 上的默认空白选项

javascript - 如何在图例中的所有系列旁边添加图标

javascript - socket.io发出返回相同的值

c - 使用数组的段错误

C:查找字符串中的特定字符

JavaScript:如何在 for 循环期间跳过数组中的当前项? (继续?)

javascript - es6展开运算符不组合键控对象

javascript - 根据选项选择问题更改元素值