JavaScript Array Reduce

未能成功加载,请稍后再试
0/0

Once again with our array of numbers, let's say we want to calculate the sum of all these numbers in this array.

This would be similar to calculating the total cost of all the items in a shopping cart.

So each numbers here could represent the price of an item in a shopping cart.

Of course, we wouldn't have a negative number there, but you got the point.

So here's a very simple algorithm for calculating the sum of all the numbers in this array.

We'll start by declaring a variable called sum and we initialize it to 0 Next we loop over this array get each element or each number and add it to sum something like this for let n of numbers Now we want to add n to sum So we can write an expression like this sum equals sum plus n or a better way is to use the addition assignment operator so we can exclude the second sum so this is exactly like the statement we had before and finally we display sum on the console so we get five now there is a cleaner and more elegant way to write the same code using the reduce method in arrays so all these arrays have this reduce method and with This method, we can reduce all these elements in an array into a single value.

That single value can be a number, it can be a string, it can be an object, it can be anything.

In this example, we want to reduce all these elements into a single number.

That is the sum of all the numbers in this array.

So let's see how we can use the reduce method.

下载全新《每日英语听力》客户端,查看完整内容