简体   繁体   English

如何以javascript的reduce方法作为对象访问累加器

[英]How to access the accumulator in javascript's reduce method as a object

I have been struggling with why this won't work. 我一直在努力为什么这行不通。 We start as a {}, then grab the first element of the split string array. 我们以{}开始,然后获取拆分字符串数组的第一个元素。 If that object property exists, then increase the value by one. 如果该对象属性存在,则将值增加一。 If not, then create the property and set the value to 1. Any help would be really appreciated as I clearly am missing something about the reduce method. 如果不是,那么创建该属性并将其值设置为1。由于我显然缺少关于reduce方法的帮助,因此将不胜感激。

const countCharacters = string => {
    return string.split('').reduce((total, element) => {
       if (total[element]) {
           return total[element] += 1;
       } else {return total[element] = 1}
    },{});
};

If you want total to be an Object in every iteration, you need to return the object from the previous iteration 如果希望total在每个迭代中都成为一个Object,则需要返回上一个迭代中的对象

Currently your code returns a Number = which isn't the Object you started with 当前,您的代码返回一个Number =这不是您开始使用的对象

Here's what happens with your code 这是您的代码发生的情况

'abca'.split('').reduce((total, element) => {
    if (total[element]) {
        return total[element] += 1;
    } else {
        return total[element] = 1;
    }
},{});

first iteration .. total = {}, element = 'a', return total.a = 1 (which returns 1) 第一次迭代.. total = {},element ='a',返回total.a = 1(返回1)
second iteration .. total = 1, element = 'b' ... 第二次迭代.. total = 1,element ='b'...

So, you want something like: 因此,您需要类似:

const countCharacters = string => {
    return string.split('').reduce((total, element) => {
       if (total[element]) {
           total[element] += 1;
       } else {total[element] = 1}
       return total;
    },{});
};

Or, more succinctly 或者,更简洁

const countCharacters = string => string.split('').reduce((total, element) => {
    total[element] = (total[element] || 0) + 1;
    return total;
}, {});

Or, less succinctly, but a one liner 或者,不太简洁,但只有一个班轮

const countCharacters = string => string.split('').reduce((total, element) => (total[element] = (total[element] || 0) + 1, total), {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM