Replace array entry with spread syntax in one line of code?

前端 未结 6 777
情深已故
情深已故 2021-02-04 00:02

I\'m replacing an item in a react state array by using the ... spread syntax. This works:

let newImages = [...this.state.images]
newImages[4] = updatedImage
this         


        
6条回答
  •  再見小時候
    2021-02-04 00:57

    You can convert the array to objects (the ...array1), replace the item (the [1]:"seven"), then convert it back to an array (Object.values) :

    array1 = ["one", "two", "three"];
    array2 = Object.values({...array1, [1]:"seven"});
    console.log(array1);
    console.log(array2);

提交回复
热议问题