Replace element at specific position in an array without mutating it

前端 未结 7 590
感情败类
感情败类 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 09:08

    Another way could be to use spread operator with slice as

    let newVal = 33, position = 3;
    let arr = [1,2,3,4,5];
    let newArr = [...arr.slice(0,position - 1), newVal, ...arr.slice(position)];
    console.log(newArr); //logs [1, 2, 33, 4, 5]
    console.log(arr); //logs [1, 2, 3, 4, 5]

提交回复
热议问题