search

Home  >  Q&A  >  body text

javascript - Encapsulate the repeated parts of these two functions into one function?

//给数组中的每一项增加3

function addThreeForEachItem(array){

      for(var i = 0; i < array.length; i++){

        array[i] = array[i] + 3;

    }

    return array;

}

//将数组中的每一项编码

function encodeEachItem(array){

    for(var i = 0; i < array.length; i++){

        array[i] = encodeURIComponent(array[i]);

    }

    return array;

}

The two functions are very similar (duplicate). How to encapsulate the repeated parts of these two functions into one function?

大家讲道理大家讲道理2744 days ago603

reply all(3)I'll reply

  • 某草草

    某草草2017-05-19 10:11:46

    There is a native method without encapsulation

    array.map(item=>item+3)
    array.map(item=>encodeURIComponent(item))

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:11:46

    The map method that comes with JS has encapsulated your needs

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:11:46

    可以考虑给第二个参数来区分
    function repeatControl(array,param){
     for(var i = 0; i < array.length; i++){
        if(param=='addThree'){
           array[i] + = 3;
        }else{
           array[i] = encodeURIComponent(array[i]);
        }
     }
      return array;
    }

    reply
    0
  • Cancelreply