一、背景
openlayer的ol.format.filter.and( filter1,filter2, ...,filterN);函数可以实现你输入任意多个参数,然后进行交处理。
https://openlayers.org/en/latest/apidoc/module-ol_format_filter.html#.and
module:ol/format/filter.and(conditions){module:ol/format/filter/And~And}
github上add()函数的实现内容:https://github.com/openlayers/openlayers/blob/v6.1.1/src/ol/format/filter.js 30行
/**
* Create a logical `<And>` operator between two or more filter conditions.
*
* @param {...import("./filter/Filter.js").default} conditions Filter conditions.
* @returns {!And} `<And>` operator.
* @api
*/
export function and(conditions) {
const params = [null].concat(Array.prototype.slice.call(arguments));
return new (Function.prototype.bind.apply(And, params));
}
问题1:为什么add函数能做到任意个参数输入。
答: 其实这是JavaScript 的语法特点,就是只看函数名,不看函数参数的,其导致重命名函数覆盖问题:也就是同名函数,只会调用最后那个函数。
而其怎么调用函数参数呢?其实是通过function的元信息:arguments 属性:其就是用array的方式保存了传入的参数,并依次调用。
问题2: 那么现在需要解决的问题是:我现在会生成不确定个数的Filter,保存到Array 中。如果直接通过:
arrayFilters = [f1,f2,f3,..,fn] , ol.format.filter.and(arrayFilters) 的时候,会报错。
所以,怎么解决代码运行时传入当时的所有参数?
思路: 参考其“github上add()函数的实现”(最开始的代码),其实可以使用JavaScript 的函数调用方法:
比如:call , bind , apply 等等其他【待补充】
我的解决方法:
finalFilter = ol.format.filter.and.apply(this,filters); //成功
//finalFilter = new (Function.prototype.bind.apply(ol.format.filter.And,filters)); //报错
//finalFilter = ol.format.filter.and.call(this, filters); //报错
//finalFilter = ol.format.filter.and.bind(this, filters)(); //报错
//finalFilter = ol.format.filter.and.bind(this)(filters); //报错
结论:参考博客:JavaScript 中 call()、apply()、bind() 的用法

本文深入探讨了OpenLayers中的ol.format.filter.and函数,该函数允许输入多个过滤条件并进行逻辑与运算。文章详细解释了如何在JavaScript中处理不定数量的参数,通过apply方法正确调用and函数,避免了直接传递数组时的错误。
5055

被折叠的 条评论
为什么被折叠?



