首页 > 解决方案 > 这行是否: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;
};

标签: javascriptreduce

解决方案


“我想知道为什么这行: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;
};


推荐阅读