如何在js中使用reduce的字符串数组获得字符串长度的总和



如前所述,我希望通过reduce函数获得数组中字符串的总和。

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];
const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
return accumulator.length + currentValue.length;
});
console.log(sumtwo);

到目前为止,我试图得到我的两个参数的长度,但当我控制台。log它,我只是得到一个Nan。

您正在返回一个数字,因此您不需要访问accumulatorlength属性。除此之外,你还需要指定一个初始值0,这样JavaScript从一开始就知道它是一个数字,因为默认情况下,它被设置为你试图减少的数组中的第一个值(在本例中为apple)。

你的固定代码应该是这样的:

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];

const sumtwo = fruitsb.reduce((accumulator, currentValue) => {
return accumulator + currentValue.length; // accumulator is already a number, no need to access its length
}, 0); // Initial value of 0

console.log(sumtwo);

我将使用join()数组方法,然后找到长度

const fruitsb = ['apple', 'orange', 'mango', 'pineapple'];
const sumtwo = fruitsb.join('');
console.log(sumtwo.length);

最新更新