首页 > 解决方案 > 为什么我们在函数中传递匿名参数?

问题描述

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() 中?

标签: javascriptfunction

解决方案


如果您传递参数,该函数将更加灵活——它将能够处理传递给它的任何类型的输入,而不仅仅是您在其外部范围内硬编码的输入。

例如,假设您正在使用电子表格,并且经常需要从一系列年份中计算年龄。然后,使用参数传递数组显然比每次有新输入时重新声明和重新调用新函数更可取:

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.


推荐阅读