javascript - 这行是否:return acc + cur.length; 自动设置新的ACC?
问题描述
这是我的代码,它基本上限制了标题的单词。
我想知道为什么return acc + cur.length;
自动设置新值acc
而不需要将其存储到新变量中。
非常感谢!
const limitRecipeTitle = (title, limit = 17) => {
const newTitle = [];
if (title.length > limit) {
title.split(' ').reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(' ')} ...`;
}
return title;
};
解决方案
“我想知道为什么这行:return acc + cur.length; 自动设置 acc 的新值,而无需将其存储到新的 const 中。”
您将回调函数传递给.reduce()
. 该.reduce()
方法在内部调用您提供的函数并存储其返回值。
这些调用是在循环中发生的,因此循环的下一次迭代中的回调调用会获取您从上一次迭代中返回的值。
这是一个非常简化的.reduce
方法版本。
Array.prototype.myReduce = function(callback, acc) {
var i = 0;
if (arguments.length < 2) {
acc = this[0];
i = 1;
}
while (i < this.length) {
// The provided callback gets invoked with the current
// value of `acc`, and then overwrites `acc` with the
// return value so that the next iteration gets passed
// that new value.
acc = callback(acc, this[i], i, this);
i++;
}
return acc;
};
推荐阅读
- mongodb - 使用 MongoDB 投影
- sql - 如何将用户定义的函数应用于 BigQuery SQL 中的多个列?
- javascript - 稍后在代码中访问时数组为空
- python - 欧拉和改进欧拉(Heun)在精度上的区别
- cookies - 无法在服务器端 Nuxt.js 上设置 cookie
- javascript - 如何在 django 项目中使用 ajax 显示搜索结果?
- python - 在 macbook pro M1 上安装 Tensorflow 时出现“zsh:非法硬件指令 python”
- mongodb - 如何将 localhost 更改为 MongoDb 和 Heroku 主机
- django - 返回不属于 Generics.listAPIView 中任何模型的内容
- r - R:创建一个将向量的前 n 个元素大写的函数