javascript - 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))
解决方案
在这种情况下,变量 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)
推荐阅读
- youtube-api - 您如何使用 YouTube 数据 API 获取过去的直播流
- c - 二进制 int* 数组到 int 等效
- cqrs - CQRS(事件溯源):具有多个聚合的投影
- python - 将 str 添加到列表中每个数字的末尾
- javascript - 在html5 localStorage中存储十亿双/整数的数组?
- php - 如何阻止 PHP 电子邮件脚本发送垃圾邮件?
- apache - URL 重定向到文件
- ruby-on-rails - 如何理解这个 ActiveStorage 错误日志的含义?
- java - 计算字符列表中的两位数
- javascript - firebase 问题和本机反应,添加数据