首页 > 解决方案 > Javascript 生活功能

问题描述

我正在学习 JavaScript 的初学者课程,并且遇到了这段代码。但我不明白为什么 sum 需要是一个 IIFE 函数。你能帮我理解这段代码是如何工作的吗?

const sum = function() {
  return function sum(x, y, z) {
    const args = [x, y, z];
    return args.reduce((a, b) => a + b, 0);
  };
}();
console.log(sum(1, 2, 3))

标签: javascriptfunctioniife

解决方案


在这种情况下,变量 args 接受参数

const sum = function() { 
  return function sum(x,y,z) {
     const args = [1,2,3];
     return args.reduce((a,b) => a+b, 0);}; 
}();
 console.log(sum(1,2,3))

reduce() 方法为数组的每个值执行一个 reducer 函数。在这种情况下,您将获取数组的前两个元素,找到这两个元素的总和,reduce 方法将逐个处理其他元素。

其他可以更好地解释你的例子

const numbers = [175, 50, 25];

function myFunc(total, num) {
   return total - num;
} // returns 100 (175 - 50 - 25)

推荐阅读