lodash 的过滤函数是否带上下文?
Does lodash's filter function take a context?
我看过 lodash filter 文档,不清楚第三个参数是否是上下文。
我正在使用 cytoscape 插件 (dagre),它似乎将 this
作为第 3 个参数传递。当我在调用过滤器方法之前暂停执行时,定义了 this
。但是在调用中 this
是未定义的。
我查看了 underscore filter 文档,它似乎将第三个参数作为上下文。所以我有点猜测该插件最初使用下划线然后可能更改为 lodash。我正在做的项目正在使用 lodash。
我当时无法理解为什么 this
为空。它可能是项目特定的,但我只想清楚 lodash 过滤器的第三个参数。
lodash的filter的定义和underscore的filter的定义是一样的吗?从文档来看似乎不是这样。
好吧,您始终可以使用 Function.prototype.bind
来定义自己的上下文。
_.filter([…],
function (o) {
console.log(this.id); //100
//than return something based on o
return o.active
}.bind({id: 100})
);
不幸的是,lodash filter
method, unlike underscore filter
method 没有为 context
参数提供选项,因为它只需要两个参数:
Arguments
- collection (Array|Object): The collection to iterate over.
- [predicate=_.identity] (Function): The function invoked per iteration.
你可以做的是使用 .bind()
method 将回调函数绑定到所需的 context
对象,如下所示:
_.filter(array, callback.bind(context));
注:
请注意 Javascript 有自己的 Array#filter()
method,它已经提供了这个选项。
我看过 lodash filter 文档,不清楚第三个参数是否是上下文。
我正在使用 cytoscape 插件 (dagre),它似乎将 this
作为第 3 个参数传递。当我在调用过滤器方法之前暂停执行时,定义了 this
。但是在调用中 this
是未定义的。
我查看了 underscore filter 文档,它似乎将第三个参数作为上下文。所以我有点猜测该插件最初使用下划线然后可能更改为 lodash。我正在做的项目正在使用 lodash。
我当时无法理解为什么 this
为空。它可能是项目特定的,但我只想清楚 lodash 过滤器的第三个参数。
lodash的filter的定义和underscore的filter的定义是一样的吗?从文档来看似乎不是这样。
好吧,您始终可以使用 Function.prototype.bind
来定义自己的上下文。
_.filter([…],
function (o) {
console.log(this.id); //100
//than return something based on o
return o.active
}.bind({id: 100})
);
不幸的是,lodash filter
method, unlike underscore filter
method 没有为 context
参数提供选项,因为它只需要两个参数:
Arguments
- collection (Array|Object): The collection to iterate over.
- [predicate=_.identity] (Function): The function invoked per iteration.
你可以做的是使用 .bind()
method 将回调函数绑定到所需的 context
对象,如下所示:
_.filter(array, callback.bind(context));
注:
请注意 Javascript 有自己的 Array#filter()
method,它已经提供了这个选项。