javascript - 为什么我们在函数中传递匿名参数?
问题描述
var years = [1990, 1954, 1943, 1929, 1986];
function arrayCalc(arr, fn){
var result = [];
for(i = 0; i < arr.length; i++){
result.push(fn(arr[i]));
}
return result;
}
function calculateAge(el){
return 2020 - el;
}
var ages = arrayCalc(years,calculateAge);
console.log(ages);
为什么我们在函数的小括号内传递未知/匿名参数(比如这里使用了 arr 和 fn)?为什么我们不将实际名称作为参数(如 years 和 calculateAge)直接放入 arrayCalc() 中?
解决方案
如果您传递参数,该函数将更加灵活——它将能够处理传递给它的任何类型的输入,而不仅仅是您在其外部范围内硬编码的输入。
例如,假设您正在使用电子表格,并且经常需要从一系列年份中计算年龄。然后,使用参数传递数组显然比每次有新输入时重新声明和重新调用新函数更可取:
function arrayCalc(arr, fn) {
var result = [];
for (i = 0; i < arr.length; i++) {
result.push(fn(arr[i]));
}
return result;
}
function calculateAge(el) {
return 2020 - el;
}
var years1 = [1990, 1954, 1943, 1929, 1986];
console.log(arrayCalc(years1, calculateAge));
var years2 = [1990, 1991, 1993, 1994, 2000];
console.log(arrayCalc(years2, calculateAge));
const nums = [1, 2, 3];
const square = num => num ** 2;
console.log(arrayCalc(nums, square));
Another benefit is that scope should be narrowed as much as possible in most situations, for code clarity. If you can make it clear that a particular variable is only going to be used inside a function, and not outside of it, it'll be easier for others (and you!) to comprehend the intent of the code later.
A related benefit is that code is more predictable and easier to manage when functions are pure - when (among other things) their output only depends on the arguments it's passed, rather than on stuff outside.
推荐阅读
- c - C递归 - 将数字的每个数字增加1,除了数字9,它将是0
- c - 仅使用 CMake 链接创建可执行文件
- ios - Swift:带有活动表格视图的弹出窗口
- javascript - 您可以将 javascript 面板拖到浏览器窗口外吗?
- python - 'NoneType' 对象不可下标错误
- python - 绘制具有多列的数据框,同时使行成为图例
- c++ - 类成员中 T[n] 与 T* 样式数组的含义
- c# - C# linq 和 ORACLE 对点顺序的不同解释
- json - Angular 8 使用 JSON 进行足球比赛
- angular - 数据绑定值不显示的一种方式,但是在控制台记录时显示数据