Common iterative methods of JavaScript forEach, filter(), map(), reduce()

1. for、forEach

1.1 Three ways to write for traversal

  • code show as below:
    var array = [66,77,88];
    
    for(var i =0;i<array.length;i++){
          
          
    	console.log(array[i]);
    }
    
    console.log("\n============")
    
    for(var i in array){
          
          
    	console.log(array[i]);
    }
    
    console.log("\n============")
    
    for(var item of array){
          
          
    	console.log(item);
    }
    
    Insert image description here
    Insert image description here

1.2 forEach + callback function traversal

  • as follows:

    	  var array = [66,77,88];
    
          console.log("\n=====1.1=======\n\n")
    
          array.forEach(function(value){
          
          
              console.log(value);
          });
    
          console.log("\n====1.2========\n\n")
    
          array.forEach(function(value,index){
          
          
              console.log(`${
            
            index}--->${
            
            value}`);
          });
    
    
    	  function Dog(name,age){
          
          
    		  this.name = name;
    	  	  this.age = age;
    	  }
    	  var d1 = new Dog("麦兜",3);
    	  var d2 = new Dog("贝塔",2);
    	
    	  var dogArray = [d1,d2];
    
          console.log("\n\n\n=====2.1=======\n\n\n")
    
          dogArray.forEach(function(dog){
          
          
              console.log(dog);
          })
    
          console.log("\n=====2.2=======\n\n")
    
          dogArray.forEach(function(dog,index){
          
          
              console.log(index + '---->' + JSON.stringify(dog));
          })
    

    Insert image description here

1.3 forEach + arrow function traversal

  • The code is much simpler, as follows:

    var array = [66,77,88];
    
    console.log("\n=====1.1=======\n\n")
    
    array.forEach(value=>console.log(value));
    
    console.log("\n====1.2========\n\n")
    
    array.forEach((value,index)=>{
          
          
        console.log(`${
            
            index}------${
            
            value}`);
    })
    
    
    function Dog(name,age){
          
          
    	this.name = name;
    	this.age = age;
    }
    var d1 = new Dog("麦兜",3);
    var d2 = new Dog("贝塔",2);
    
    var dogArray = [d1,d2];
    
     console.log("\n\n\n=====2.1=======\n\n\n")
    
     dogArray.forEach(dog=>console.log(dog))
    
     console.log("\n=====2.2=======\n\n")
    
     dogArray.forEach((dog,index)=>console.log(index + '---' + JSON.stringify(dog)))
    

    Insert image description here

2. filter()

2.1 Introduction

  • Introduction:
    The filter() method creates a shallow copy of a portion of the given array containing all elements of the test implemented by the provided function.
  • grammar
    filter(callbackFn)
    filter(callbackFn, thisArg)
    
  • parameter, return value
    Insert image description here
  • describe
    Insert image description here
  • Refer to the official website:
    Official website - Array.prototype.filter() .

2.2 Example 1 - Simple filtering

  • code show as below:
    const array = [66,77,88];
    
    //1. 箭头函数回调
    const newArray_1 = array.filter(arr => arr > 70);
    
    //2. 匿名函数回调
    const newArray_2 = array.filter(function(arr){
          
          
        return arr > 70;
    });
    
    //3. 普通函数回调
    function myFilter(val){
          
          
        if(val > 70){
          
          
            return true;
        }else{
          
          
            return false;
        }
    }
    const newArray_3 = array.filter(myFilter);
    
    Insert image description here

2.3 Example 2 - Behavior of the filter() method when modifying an array

  • code show as below:

    console.log("\n\n====1. 排除第一个元素=====\n\n");
    
     const numArray_1 = [6,7,8];
    
     const new_numArray_1 = numArray_1.filter((item,index,array)=>{
          
          
         array[index+1] += 10; //修改的是下一个元素,影响了初始数组,但是数组中第一个数据不动,其余+10
         return item > 10; //除了第一个元素,其余判断时都已经 +10 了
     });
     console.log(numArray_1);//[6, 17, 18, NaN]
     console.log(new_numArray_1);// [17, 18]
    
     console.log("\n\n====2. 所有元素+10 后都判断=====\n\n");
    
     const numArray_2 = [6,7,8];
    
     const new_numArray_2 = numArray_2.filter((item,index,array)=>{
          
          
         array[index] += 10;  //从当前元素就改变,即:该变了数组中所有元素
         return array[index] > 10; 
         /**需要注意的是:
          * 这个只是过滤条件,装入新数组的是item,
          * 当前循环时item的值并没有改变(当前下标在数组中的元素值没有改变),
          * 所以装入新数组的是老数据
          */
     });
     console.log(numArray_2);//[16, 17, 18]
     console.log(new_numArray_2);//[6, 7, 8]
    

    Insert image description here

2.4 Example 3 - Searching in an array

  • The following example uses filter() to filter the contents of an array based on search criteria.
  • code show as below:
     <script>
         const pets = ['dog-麦兜','dog-泡泡','cat-阿苔','dog-lucky','cat-点点'];
    
         const strs = ['I love you','love?','no','he is hate','love me?'];
    
         function filterIterms(array,query){
          
          
             return array.filter(arr => arr.includes(query.toLowerCase()));
         }
    
         let dogs = filterIterms(pets,'dog');
         let cats = filterIterms(pets,'cat');
         let loveStr = filterIterms(strs,'LOve');
    
         console.log(dogs);
         console.log(cats);
         console.log(loveStr);
     </script>
    
    Insert image description here

3. map()

3.1 Introduction

  • Introduction:
    The map() Methodcreate a new array, this new array consists of each element in the original arrayThe return value after calling the provided function oncecomposition.
  • grammar
    map(callbackFn)
    map(callbackFn, thisArg)
    
  • parameter, return value
    Insert image description here
  • describe
    Insert image description here

3.2 Example 1 - Find 2 times each element in the array

  • code show as below:

     const numArray = [1,3,5,7];
    
     const new_numArray = numArray.map(num => num*2 );
    
     console.log(numArray);
     console.log(new_numArray);
    

    Insert image description here

3.3 Example 2 - Using map to reformat objects in an array

  • code show as below:

     const kvArray = [
         {
          
           key: 1, value: 10 },
         {
          
           key: 2, value: 20 },
         {
          
           key: 3, value: 30 },
     ];
    
     const reformattedArray = kvArray.map(( {
           
           key, value} )=>{
          
          
         return ({
          
          [key]: value});
     });
    
     console.log(kvArray);
    
     console.log("\n\n======重新格式化数据之后=====\n\n");
     console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
    

    Insert image description here

  • For more usage, please refer to the official website:
    Official website - Array.prototype.map() .

4. reduce()

4.1 Introduction

  • Instructions for use
    • The reduce() method sequentially executes a provided reducer function on each element in the array. Each time the reducer is run,Pass in the calculation result of the previous element as a parameter, and finally its resultSummaryfor a single return value.
    • When the callback function is executed for the first time, there is no "last calculation result".
    • Start looping from the first element or the second element, depending on whether the initial value is passed:
      • If the initial value is passed:
        the callback function is executed from the element whose index is 0 in the array, and the summary result is: 初试值 + 数组中的每个元素.
      • If no initial value is passed:
        the element with index 0 of the array will be used as the initial value, and the iterator will start executing from the second element.
  • grammar
    reduce(callbackFn)
    reduce(callbackFn, initialValue)
    
  • parameter + return value
    Insert image description here
    Insert image description here
  • describe
    Insert image description here

4.2 Example 1 - Sum of array elements

  • code show as below:

    <script>
        
        const numArray = [1,2,3,4];
    
        /**
         * 没有初试值时:
         * 1. accumulator的值:在第一次调用时,如果没有指定 初始值 则为 数组中的第一个值;
         * 2. 并且 callbackFn 从数组中的第二个值作为 currentValue 开始执行。
         */
        const result_1 = numArray.reduce((accumulator, currentValue)=>{
          
          
            console.log(currentValue);
            return accumulator + currentValue;
        });
    
        console.log("结果:" + result_1);//没有初试值:1+2+3+4 = 10
    
    
        console.log("\n\n\n========给初试值的情况======\n\n\n");
    
        /**
         * 有初试值:
         * 1. accumulator的值:在第一次调用时,如果指定了 初始值 则为指定的初始值
         * 2. callbackFn 从数组中的第一个值作为 currentValue 开始执行
         */
        const result_2 = numArray.reduce((accumulator, currentValue)=>{
          
          
            console.log(currentValue);
            return accumulator + currentValue;
        },200); //指定初试值:200
    
        console.log("结果:" + result_2);//有初试值:200+1+2+3+4 = 210
    
    </script>
    

    Insert image description here

4.3 Example 2 - Finding the sum of an attribute value in an object array

  • code show as below:
        <script>
    
            function Dog(dogName,dogAge){
          
          
                this.dogName = dogName,
                this.dogAge = dogAge
            }
    
            let dog_1 = new Dog('麦兜',3);
            let dog_2 = new Dog('泡泡',5);
            let dog_3 = new Dog('大牙',2);
    
            const dogs = [dog_1,dog_2,dog_3];
    
            // console.log(dogs);
            
            const sumAge = dogs.reduce((pre,cur)=>{
          
          
                return pre + cur.dogAge;
            },0);
    
            console.log(sumAge);
            
        </script>
    
    Insert image description here

4.4 Example 3 - Flattening nested arrays

  • as follows:

      //展平嵌套数组
      const array = [[1,2],[3,4],[5,6]];
    
      const new_array = array.reduce((accumulator, currentValue)=>{
          
          
          return [...accumulator,...currentValue];
      });
    
      console.log(new_array);
    

    Insert image description here

4.5 Example 4 - counting the number of occurrences of a value in an object

  • as follows:

      //统计对象中值的出现次数
    
      const strs = ['you','love','I','love','beautiful','go'];
    
      const count_result = strs.reduce((countSum,currentStr)=>{
          
          
          if(currentStr === 'love'){
          
          
              return countSum + 1;
          }
          return countSum;
      },0);
    
      console.log("love 单词出现的次数:" + count_result);
    

    Insert image description here

4.6 Example 5 - Array deduplication

  • as follows:
     //去重
     const strs = ['you','love','go','love','beautiful','go'];
    
     let result = strs.reduce((countSum,currentStr)=>{
          
          
         if(countSum.includes(currentStr)){
          
          
             return countSum;
         }else{
          
          
             return [...countSum,currentStr];
         }
     },[]);
    
     console.log(strs);
     console.log(result);
    
    Insert image description here
    For more usage, please refer to the official website:
    Official website - Array.prototype.reduce() .

Guess you like

Origin blog.csdn.net/suixinfeixiangfei/article/details/132746531