Replace element at specific position in an array without mutating it

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

    Here is how I'd like to do it:

    function update(array, newItem, atIndex) {
        return array.map((item, index) => index === atIndex ? newItem : item);
    }
    

    Generally, Array-spread operation produces few temporary arrays for you, but map doesn't, so it can be faster. You can also look at this discussion as a reference

提交回复
热议问题