Replace element at specific position in an array without mutating it

前端 未结 7 884
感情败类
感情败类 2021-01-31 08:20

How can the following operation be done without mutating the array:

let array = [\'item1\'];
console.log(array); // [\'item1\']
array[2] = \'item2\'; // array is         


        
7条回答
  •  眼角桃花
    2021-01-31 08:57

    The fast way

    function replaceAt(array, index, value) {
      const ret = array.slice(0);
      ret[index] = value;
      return ret;
    }
    

    See the JSPerf (thanks to @Bless)

    Related posts:

    • Javascript fastest way to duplicate an Array - slice vs for loop
    • https://github.com/lodash/lodash/issues/2053#issuecomment-188776090

提交回复
热议问题