ECMAScript defines 5 iteration methods for arrays. Each method receives two parameters: a function to be run with each item as argument, and an optional scope object as the context in which the function is run (affecting the value of this in the function). The function passed to each method receives three parameters: the array element, the element index, and the array itself. Depending on the specific method, the results of this function may or may not affect the method's return value. The 5 iteration methods of the array are as follows.
1. Map method: Run the passed function on each item of the array and return an array composed of the results of each function call.
It can also be understood as: after performing special processing on each element in the array, return a new array .
For example:
before simplifying the price array:
let prices=[50,80,90] prices=prices.map((item,index)=>{ return item+"yuan" })
After the abbreviation of
console.log(prices):
let price=[50,80,120] //Add "yuan" after the unit price price=price.map(item=>item+"yuan") console.log(price)//The output is ['50 yuan', '80 yuan', '90 yuan']
Its application scenario is for example: WeChat applet Douban Film Review
uses the map method to replace xxx with www
replace() method Used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
let movies=[{id:1,name:"Shawshank Redemption",imgUrl:"http://xxx.douban.com/1.jpg"},{id:2,name:"Shawshank Redemption",imgUrl :"http://xxx.douban.com/2.jpg"},{id:3,name:"Shawshank Redemption",imgUrl:"http://xxx.douban.com/1.jpg"}] movies=movies.map(item=>{ item.imgUrl=item.imgUrl.replace("xxx","www") return item }) console.log(movies)
2. Filter method: Run the passed function on each item of the array. The items that the function returns true will form an array and return.
It can also be understood as: filter out the elements in the array that meet the requirements and return a new array
let scores=[80,59,10,55,90,88] let arr=scores.filter(item=>{ if(item>60){ return true } }) console.log(arr)//Output is as shown below:
Output is as shown below and filter out arrays less than 60
After abbreviation:
let scores=[80,59,10,55,90,88] let arr=scores.filter(item=>item>=60) console.log(arr)//(3) [80, 90, 88]
In its application scenario, you can place an array of city names and then search for keywords. This is only for when the data is small. I will publish a book about the example later. The application scenarios of the management system will include keyword searches for reference.
Some is translated in English as some, and every is translated as all, each, so the some method will return true as long as one of them is true. On the contrary, the every() method must all return true before it can return. true, even if there is one false, false will be returned.
During the array judgment process, it is judged whether each element of the whole meets a basic requirement.
Some method: one true and true, as long as one of them matches, it will return true.
every method: one false is false, as long as one of them does not meet the requirements, it will return false
//let the scores of all students in a class to see if everyone has passed let scores=[80,49,12,50,69 ] let result=scores.every(item=>item>=60) console.log(result)//Return false Not all are passed.
Usage scenarios: Before the front-end validator submits an AJAX request, it usually needs all verifications to pass before it can be sent. There will be a separate follow-up article about code examples. Front-end data validator.
5. Reduce method: ECMAScript provides two merge methods for arrays: reduce() and reduceRight(). Both methods iterate over all items of the array and construct a final return value based on this. The reduce() method traverses from the first item to the last item in the array. And reduceRight() traverses from the last item to the first item. It can also be simply understood as: integrating the elements in the array and returning a new content.
Both methods accept two parameters: a merge function to be run on each item, and an optional initial value to start the merge from. The functions passed to reduce() and reduceRight() receive four parameters: the previous merged value, the current item, the index of the current item, and the array itself. Any value returned by this function will be used as the first argument in the next call to the same function. If the optional second parameter (as the merge starting value) is not passed to these two methods, the first iteration will start from the second item of the array, so the first parameter passed to the merge function is the array. The first item, the second parameter is the second item of the array.
First understand the concept through the following code:
the meaning of the four parameters in the following code:
prev: the result returned by the previous operation
item: the element of this operation
index: the index value of the element of this operation
array: the array of the current operation
let arr =[20,40,50,21] let values=arr.reduce((prev,item,index,array)=>{ console.log("prev"+prev) console.log("item"+item) console.log("index"+index) console.log("array"+array) console.log("____________________") })
The output is:
Why does it only loop three times? Prev can set a default value. If the default value is not set, the first element will be the first prev.
Why does prev get undefined in the second and third loops? In the second loop, you have to get the return value of the first loop because the return was not set the first time, so you get undefined. And so on.
If you understand the above, then we start to implement array summation:
let arr=[20 ,40,50,21] let values=arr.reduce((prev,item,index,array)=>{ console.log("prev"+prev) return prev+item //Give a return and loop four times. The first time the output prev is 20, the second time 40+20 is 60, the third time is 110 and the last time it outputs 131. }) console.log(values) //131
When must the default value of prev be set?
Add <li> </li> to each array element
let arr=["Eason Chan","Miriam Yeung","Juji Ku","Hacken Lee"] //Set a default value for prev: Function 1. All elements participate in the loop 2. Determine the return content let result=arr.reduce((prev,item)=>{ //console.log(prev) return prev+"<li>"+item+"</li>" },"")//Add an empty string console.log(result)//<li>Eason Chan</li><li>Miriam Yeung</li><li>Juji Ku</li><li>Keqin Li</li> li>
Let’s take another case:
use reduce to achieve array deduplication, create an empty array, traverse the original array in sequence, insert what is not in the empty array, and what is not inserted will no longer be inserted
let arr=["Zhang San"," Li Si","Li Si","Wang Er","Li Si","Mazi","Zhang San"] let result=arr.reduce((prev,item)=>{ //Includes determines whether there is a specified element and returns t, otherwise it returns f. if(!prev.includes(item)){ prev.push(item) //.push() adds a new item to the array} return prev },[])//Set a default empty array console.log(result)//(4) ['Zhang San', 'Li Si', 'Wang Er', 'Mazi']
Another case: (reduce method You can do many things)
count the number of occurrences of characters: see the code below
let arr=["a","b","a","c","b","a","c"] //Return an object to count the number of occurrences of each character {a:2,w:3} let result=arr.reduce((prev,item)=>{ // //Determine whether the object has corresponding attributes if(item in prev){ //Find the corresponding attribute value++ prev[item]++ //If you want to set or get object attributes in the future, this attribute will be represented by a variable in the form of brackets []++, if it is directly.The attribute name will be in the form of.}else{ prev[item]=1 } return prev },{}) console.log(result)//{a: 3, b: 2, c: 2}