Javascript reduce() - return 行的作用是什么?

Javascript reduce() - What does the return line do?

我知道它确实在最基本的示例中减少了 () 但在这样的示例中却没有,尤其是 return 行。如果有人可以解释它是如何工作的,或者举一个更容易理解的例子来说明 return 是相同的结果,那就太好了。

var line = 'abazzzzax'
var obj = line.split('').reduce(function(p, c){
    return (p[c] = ++p[c] || 1, p);
}, {});
console.log(obj)
// Output => { a: 3, b: 1, z: 4, x: 1 }

本例中的 reduce 函数接受 2 个参数。

p --> 初始状态为 {}

c --> 每次迭代的值 a , b , a .....

p[c] = ++p[c] || 1 //If the `key` is already available we increment it by 1 or set it to 1.

所以我们首先更新它,return包含更新对象的p,这是由于逗号运算符。

函数内部可以这样重写:

var obj = line.split('').reduce(function(p, c){
    if (!p[c]) {
        p[c] = 1;
    } else {
        ++p[c];
    }
    return p;
}, {});

拆分这个表达式:

p[c] = ++p[c] || 1

p[c]不存在时,则值为undefined++(undefined) returns NaN 是一个假语句,所以 p[c] 的值将是 1。当 p[c] 确实存在时,则该值递增,然后重新分配给自己。像 i = ++i 这样的东西在我看来有点令人困惑。

最后,逗号运算符允许您按从左到右的顺序 运行 表达式,因此返回最终表达式,即跟踪出现次数的 p 对象。

它计算字符串中每个字符的出现次数。

基本上是

if accumulator[character] exists, increase number stored in accumulator[character] by 1 (this happens if we have set it already to 1, somewhere in the past, because otherwise it will not exist)
else set accumulator[character] to 1 (this happens when we notice a first character of a new kind)
return accumulator object