Replace element at specific position in an array without mutating it

前端 未结 7 597
感情败类
感情败类 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:13

    You can simply set up a a new array as such:

    const newItemArray = array.slice();
    

    And then set value for the index which you wish to have a value for.

    newItemArray[position] = newItem
    

    and return that. The values under the indexes in-between will have undefined.

    Or the obviously alternative would be:

    Object.assign([], array, {: newItem});
    

提交回复
热议问题