Home  >  Article  >  Web Front-end  >  What are the 4 commonly used methods for adding new arrays in es6?

What are the 4 commonly used methods for adding new arrays in es6?

青灯夜游
青灯夜游Original
2022-04-19 14:24:073492browse

The four commonly used new methods for arrays in es6 are: 1. forEach(), which is used to traverse the array with no return value; 2. filter(), which filters out values ​​in the array that do not meet the conditions; 3 , map(), traverses the array and returns a new array; 4. reduce(), performs some calculation on the first and last two items of the array, and then returns its value.

What are the 4 commonly used methods for adding new arrays in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

There are four new very practical array methods in ES6, including: forEach, filter, map, and reduce.

1.forEach

Traverse the array, no return value, do not change the original array, just traverse - equivalent to for loop traversal

 let arr=[23,44,56,22,11,99]
   let res=arr.forEach(item=>{
     console.log(item);
     //23,44,56,22,11,99
   })
   let res2=arr.forEach((item,index)=>{
     console.log(item,index);
     //23 0
     //44 1
     //....
   })

What are the 4 commonly used methods for adding new arrays in es6?

2.filter:

filter() function filters out values ​​in the array that do not meet the conditions , if the callback function returns true, leave it and return a new array without changing the original array! ! ! Can be used to deduplicate arrays

   let arr = [1,5,2,16,4,6]
   //1.找出数组中的偶数
   let newArr=arr.filter((v,i)=>
     v%2==0)
     console.log(newArr,'newArr');//2,16,4,6

   //2.过滤器 保留为TRUE的结果
   let arrTue=[13,14,9,33]
   let newArr2=arrTue.filter(item=>(item%3===0)?true:false)
   console.log(newArr2,'newArr2');//9,33
   //3.利用filter去重‘
 // 第一种
   let arr3=[2,3,5,1,2,3,4,5,6,8],newArr3
   function unique(arr){
    const res = new Map()
    return arr.filter((item)=>
      !res.has(item) && res.set(item,1)
    )
    }
   console.log(newArr3=unique(arr3),'newArr3');//2,3,5,1,4,6,8
//第二种
  let testArray = [
        {key:"01",name:'张三'},
        {key:"02",name:'小李'},
        {key:"03",name:'小罗'},
        {key:"04",name:'张三'},
        {key:"03",name:'小李'},
      ];
      let deduplicationAfter = testArray.filter((value,index,array)=>{
      //findIndex符合条件的数组第一个元素位置。
        return array.findIndex(item=>item.key === value.key && item.name === value.name) === index
      })
      console.log(deduplicationAfter)

What are the 4 commonly used methods for adding new arrays in es6?

3.map:

map traverses the array and returns A new array, without changing the original array, mapped one to one, mapped to a new array

let arr = [6,10,12,5,8]
let result = arr.map(function (item) {
    return item*2
})
let result2 = arr.map(item=>item*2) // es6的箭头函数简写,若想了解,后面的文章有介绍
console.log(result)
console.log(result2)

let score = [18, 86, 88, 24]
let result3 = score.map(item => item >= 60 ? '及格' : '不及格')
console.log(result3)

What are the 4 commonly used methods for adding new arrays in es6?

4.reduce:

reduce() summarizes a bunch of them into one (for example, calculating the total, calculating the average), reduce makes the two items before and after the array perform some calculation, and then returns its value and continues the calculation. The original array is not changed and the final result of the calculation is returned. If no initial value is given, traversal starts from the second item of the array

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]) , the first parameter callback function, the second parameter initial value

4.1Sum

//第一种给定初始值
       var arr = [1, 3, 5, 7];
        // 原理: 利用reduce特性 prev初始值设置0 并把函数的返回值再次带入函数中
        var sum = arr.reduce(function (tmp, item,index) { // prev 初始为0 以后则为函数返回的值
          console.log(tmp,item,index);
		    //  0 1  0
			//	1 3  1
			//	 4 5  2
			//	 9 7  3
            return tmp + item; // 数组各项之间的和
        }, 0);
       console.log(sum); //16
   //第二种不给初始值
   var arr2 = [1, 3, 5, 7]
	var result = arr2.reduce(function (tmp, item, index) {
	    //tmp 上次结果,item当前数,index次数1开始
	    console.log(tmp, item, index)
	        //1 3 1 
		   // 4 5 2 
		   // 9 7 3 
	    return tmp + item;
	})
console.log(result,)   //16

4.2 Find the average

var arr = [1, 3, 5, 7]
var result = arr.reduce(function (tmp, item, index) {
  console.log(tmp,item,index);
  // 1 3  1
 //  4 5  2
 //  9 7  3
    if (index != arr.length - 1) { // 不是最后一次
        return tmp + item
    } else {
        return (tmp + item)/arr.length
    }
})
console.log(result,'[[[u99')  // 平均值  4

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What are the 4 commonly used methods for adding new arrays in es6?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is es6 modularityNext article:What is es6 modularity