Array.with 로 배열복사와 변경을 한번에!

dev.horang🐯·2024년 3월 29일
2

기술로그

목록 보기
16/17
post-thumbnail

web.dev링크

web.dev 블로그에 올라온 Array.prototype.with 에 대해 설명한 내용을 정리한 것입니다.

가끔 web.dev에 올라오는 기술 포스트들을 보면서 이해할 수 있는것들을 이해해 보려 하는데 올해 올라온 기술로그 중 Array.prototype.with 에 대해 기술해 둔 기술로그를 발견하여 내가 이해한 대로 정리해 보려한다.

Array.prototype.with(index, value)

는 Array를 복사하고 복사된 복사본의 index 에 있는 값을 value로 바꿔주는 역할을 한다.

const ages = [10, 15, 20, 25];

const newAges = ages.with(1, 16);
console.log(newAges); // [10, 16, 20, 25]
console.log(ages); // [10, 15, 20, 25] (unchanged)

기존에 위의 과정을 수행하려면

const ages = [10, 15, 20, 25];
const newAges = [...ages];

newAges.splice(1,1,16)
console.log(newAges); // [10, 16, 20, 25]
console.log(ages); // [10, 15, 20, 25] 

의 한 과정을 거쳤어야 했지만 with 를 사용하면서 복사, 변경의 과정을 한번에 처리 가능하게 되었다. 당장은 어떤 상황에서 써야 이득일지 모르겠지만 기억해 둔다면 언젠가 아! 이런 메쏘드가 있었지 하면서 사용 할 날이 오지 않을까 싶다!

profile
좋아하는걸 배우는건 신나🎵

0개의 댓글