JavaScript/React
[Spread Operator] 배열에 특정한 인덱스의 아이템 교체
이쥬우
2023. 5. 3. 15:56
728x90
let arr = [1,2,3,4,5];
이 배열의 2번째 인덱스를 10으로 교환해보자. 아래와 같이
[1,2,10,4,5];
해결
const index = 2;
const newVal = 10;
arr = [
...arr.slice(0, index),
newVal,
...arr.slice(index + 1)
]
리액트 setState에서의 사용 예시
const newfile = {
s3KeyThumbnail: 'blahblah.jpg';
size: 1024,
ext: 'jpg'
}
this.setState(state => ({
...state,
files: [
...state.files.slice(0, index),
newFile,
...state.files.slice(index + 1)
]
}));
728x90