繁体   English   中英

限制Javascript函数接受的参数数量

[英]Limit Number of Parameters a Javascript Function Accepts

如何限制Javascript函数接受的参数数量?

因此,此代码段仅记录不包括索引和数组的每个值:

 const names = ["John", "Jack", "Jake"] names .map(console.log) 

Javascript没有提供明确的方法来限制函数接受的参数数量。

但是,您可以通过将原始函数包装在箭头函数中来完成此操作,如下所示:

 const log1 = first => console.log(first) const log2 = (first, second) => console.log(first, second) // ... const names = ["John", "Jack", "Jake"] names .map(log1) 

一种更可重用和可伸缩的方法是创建一个limitParams函数,该函数将给定函数接受的参数数量限制为指定数量:

 const limitParams = n => f => (...params) => f(...params.slice(0, n)) const log1 = limitParams(1)(console.log) const log2 = limitParams(2)(console.log) // ... const names = ["John", "Jack", "Jake"] names .map(log1) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM