Home >Web Front-end >JS Tutorial >Summary of knowledge points about new methods in ES6 arrays
This article brings you relevant knowledge about javascript, which mainly introduces the issues related to the new methods of es6 arrays, including iteration methods, merge methods, etc. Let’s talk about it together Take a look, hope it helps everyone.
[Related recommendations: javascript video tutorial, web front-end】
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
can also be understood as : After performing special processing on each element in the array, return a new array.
For example: price array
Before simplification:
let prices=[50,80,90] prices=prices.map((item,index)=>{ return item+"元" }) console.log(prices)
After abbreviation:
let price=[50,80,120] //在单价后面添加上"元" price=price.map(item=>item+"元") console.log(price)//输出为['50元', '80元', '90元']
Its application scenarios are such as: WeChat applet Douban Film Review
Use the map method to replace xxx with www
replace() method is used to replace some characters with other characters in a string, or replace a string that matches a regular expression substring.
let movies=[{id:1,name:"肖申克的救赎",imgUrl:"http://xxx.douban.com/1.jpg"},{id:2,name:"肖申克的救赎",imgUrl:"http://xxx.douban.com/2.jpg"},{id:3,name:"肖申克的救赎",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.
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)//输出如下图:
The output is as shown below Filter out the arrays less than 60
After the abbreviation:
let scores=[80,59,10,55,90,88] let arr=scores.filter(item=>item>=60) console.log(arr)//(3) [80, 90, 88]
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 give a library management system after the example. The application scenarios will include keyword search, you can refer to it.
some is translated in English as some, and every is translated as all, each, so the some method will work as long as one of them is true. Returns true. On the contrary, the every() method must return true before it can return true. Even if there is one false, it will return false
In the judgment process of the array, judge whether each element of the whole is all All meet a basic requirement
some method: one is true and true, as long as one of them meets the requirement, it returns true
every method: one false is false, as long as one of them does not meet the requirement, it returns false
//let一个班的所有学生的成绩 看看是否所有人都及格了 let scores=[80,49,12,50,69] let result=scores.every(item=>item>=60) console.log(result)//返回false 所有并不是都及格了
Usage scenario: Front-end validator
Before submitting an AJAX request, it is usually required that all verifications pass before it can be sent. A subsequent article about code examples will have a separate front-end data validator.
5. Reduce method: ECMAScript provides two merging 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 receive two parameters: the merge function that will be run on each item, and an optional initial value as the starting point for the merge. 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:
为什么只循环了三次?prev因为可以设置默认值,如果不设置默认值,那么第一个元素就作为第一个prev
为什么第二次循环和第三次循环时prev拿到undefined呢?在第二次循环时 得拿到第一次循环的return值 因为第一次没有设置return 所以拿到undefined 以此类推
如果上面的理解了,那么我们就开始实现数组求和:
let arr=[20,40,50,21] let values=arr.reduce((prev,item,index,array)=>{ console.log("prev"+prev) return prev+item //给个return 循环四次 第一次输出prev是20,第二次40+20是60,第三次是110 最后一次输出131 }) console.log(values) //131
什么时候必须设置prev的默认值呢?
给每一个数组元素添加
let arr=["陈奕迅","杨千嬅","古巨基","李克勤"] //给prev设置默认值:作用1.所有元素参加循环 作用2.确定返回内容 let result=arr.reduce((prev,item)=>{ //console.log(prev) return prev+"<li>"+item+"</li>" },"")//加一个空字符串 console.log(result)//<li>陈奕迅</li><li>杨千嬅</li><li>古巨基</li><li>李克勤</li>
再来个案例:
利用reduce实现数组去重,创建一个空数组,把原有数组依次遍历,空数组没有的就插入进去,有的就不再插入了
let arr=["张三","李四","李四","王二","李四","麻子","张三"] let result=arr.reduce((prev,item)=>{ //includes判断是有具有指定元素 有返回t 没有返回f if(!prev.includes(item)){ prev.push(item) //.push()向数组添加一个新项目 } return prev },[])//设置一个默认空数组 console.log(result)//(4) ['张三', '李四', '王二', '麻子']
再来个案例:(reduce方法可以做很多事情)
统计字符的出现次数:见下码
let arr=["a","b","a","c","b","a","c"] //返回一个对象 统计每一个字符的出现次数 {a:2,w:3} let result=arr.reduce((prev,item)=>{ // //判断对象 是否存在对应的属性 if(item in prev){ //找到对应属性值 ++ prev[item]++ //如果将来要设置或者获取对象属性时,这个属性由变量表示的时候用中括号的形式[]++,如果直接是.属性名称用.的形式 }else{ prev[item]=1 } return prev },{}) console.log(result)//{a: 3, b: 2, c: 2}
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Summary of knowledge points about new methods in ES6 arrays. For more information, please follow other related articles on the PHP Chinese website!