课程: Mastering Web Developer Interview Code

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

How would you use JavaScript reduce()?

How would you use JavaScript reduce()?

- [Narrator] Reduce is a higher order function just like the map method we covered in the previous week. Now it's the sign to solve a common problem going over a list of elements and retrieving a single value related to them as the result. So let's take a look at how we would do that with traditional JavaScript. So you probably create something like a variable to hold a running total and then you will create some sort of array to hold the list of elements you want to go through. And then you would use perhaps something like a for loop to iterate through those different array items so you would maybe take that total value and continue to add the values of each of the elements in the array. This is a little bit messy and map is designed to solve this problem. That is a very common pattern in JavaScript. So let's take a look at how that looks with reduce. Now, reducing we'll take a callback where you can pass along a…

内容