JavaScript: 解决问题: 解决在程序运行时,为函数 动态的传入不同个数的参数

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

一、背景

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() 的用法

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值