Background:
The shopping cart module of a recent small program just uses several methods of array, so with this project, we will talk about the common array traversal, and how to use the corresponding methods when appropriate.
Practical examples:
Map: format returned data
One of the most common items in map is the peer interfaceReturn data in format processingIn this project, the data returned by the backend interface is timestamp, but the front end needs to display the format as YYYY-HH-MM, so you can process the data directly through the map before assigning, and return a new array. Since the Map only returns the part that you processed, you also need to pass the original object through ES6 syntax… The expansion operator does the deconstruction, so that the processed data overwrites the original data and the original data is not lost in the new array.
Two: filter: filters data
In this project, I need to calculate the total consumption points of the goods in the current shopping cart list, but the list contains the goods that have been removed/sold out, so we can pass the calculation beforeFilter Filters the list data firstTo filter out removed/sold out items, the flterGoods function returns a filtered array (status true and stock not 0 are items on the shelf), which we call before calculating the total points consumed.
3: some: returns true as long as there is a match in the data, and exits the loop.
The product demand in shopping cart is that the list contains the removed/sold out products. When the user clicks the button, it has to give a prompt for the user to delete the removed/sold out products and then settle the account, so it is usedSome of the benefits ofIs that whenReturns true if one of the items in the list meets the criteria and exits the loopIt is more efficient.
ForEach: similar to the for loop, it iterates through each item, notice: undefined;
Here, the total consumption points and total number of goods in the item list array processed by filter are calculated, which are used as the quantity of goods behind the shopping cart and the required points display, so forEach is used. Do something to each of these;
conclusion
The most common usage of array methods in projects is these. In fact, the usage is very simple, and the difficult thing is to use which situation. As the saying goes, many things will be messy, but after reading this article combined with the actual situation, I hope you can be more transparent about several API usage;