如何访问 javascript 的 reduce 方法中的累加器作为对象
How to access the accumulator in javascript's reduce method as a object
我一直在纠结为什么这行不通。我们从 {} 开始,然后获取拆分字符串数组的第一个元素。如果该对象 属性 存在,则将值增加 1。如果没有,则创建 属性 并将值设置为 1。非常感谢任何帮助,因为我显然遗漏了一些关于 reduce 方法的内容。
const countCharacters = string => {
return string.split('').reduce((total, element) => {
if (total[element]) {
return total[element] += 1;
} else {return total[element] = 1}
},{});
};
如果您希望total
在每次迭代中都是一个对象,您需要return上一次迭代的对象
目前您的代码return是一个数字 = 这不是您开始使用的对象
这是您的代码所发生的情况
'abca'.split('').reduce((total, element) => {
if (total[element]) {
return total[element] += 1;
} else {
return total[element] = 1;
}
},{});
第一次迭代.. total = {}, element = 'a', return total.a = 1 (which returns 1)
第二次迭代 .. total = 1, element = 'b' ...
所以,你想要这样的东西:
const countCharacters = string => {
return string.split('').reduce((total, element) => {
if (total[element]) {
total[element] += 1;
} else {total[element] = 1}
return total;
},{});
};
或者,更简洁
const countCharacters = string => string.split('').reduce((total, element) => {
total[element] = (total[element] || 0) + 1;
return total;
}, {});
或者,不那么简洁,但是一个衬垫
const countCharacters = string => string.split('').reduce((total, element) => (total[element] = (total[element] || 0) + 1, total), {});
我一直在纠结为什么这行不通。我们从 {} 开始,然后获取拆分字符串数组的第一个元素。如果该对象 属性 存在,则将值增加 1。如果没有,则创建 属性 并将值设置为 1。非常感谢任何帮助,因为我显然遗漏了一些关于 reduce 方法的内容。
const countCharacters = string => {
return string.split('').reduce((total, element) => {
if (total[element]) {
return total[element] += 1;
} else {return total[element] = 1}
},{});
};
如果您希望total
在每次迭代中都是一个对象,您需要return上一次迭代的对象
目前您的代码return是一个数字 = 这不是您开始使用的对象
这是您的代码所发生的情况
'abca'.split('').reduce((total, element) => {
if (total[element]) {
return total[element] += 1;
} else {
return total[element] = 1;
}
},{});
第一次迭代.. total = {}, element = 'a', return total.a = 1 (which returns 1)
第二次迭代 .. total = 1, element = 'b' ...
所以,你想要这样的东西:
const countCharacters = string => {
return string.split('').reduce((total, element) => {
if (total[element]) {
total[element] += 1;
} else {total[element] = 1}
return total;
},{});
};
或者,更简洁
const countCharacters = string => string.split('').reduce((total, element) => {
total[element] = (total[element] || 0) + 1;
return total;
}, {});
或者,不那么简洁,但是一个衬垫
const countCharacters = string => string.split('').reduce((total, element) => (total[element] = (total[element] || 0) + 1, total), {});