[JavaScript] splice() ํ•จ์ˆ˜

fejiguยท2022๋…„ 9์›” 3์ผ
1

Javascript

๋ชฉ๋ก ๋ณด๊ธฐ
20/21


๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ splice() ํ•จ์ˆ˜๋ฅผ ์ œ๋Œ€๋กœ ์•Œ์ง€ ๋ชปํ•ด ๋‹ค์‹œ MDN๋ฅผ ๊ฒ€์ƒ‰ํ•˜๋Š” ๋‚˜์˜ ๋ชจ์Šต์„ ๋ณด๊ณ  ๋ธ”๋กœ๊ทธ์— ์ •๋ฆฌํ•ด๋‘๋ฉฐ ๋ณต์Šตํ•˜๊ณ ์ž ํ•œ๋‹ค


๐Ÿ”Ž splice()๋ž€

splice() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์˜ ๊ธฐ์กด ์š”์†Œ๋ฅผ ์‚ญ์ œ ๋˜๋Š” ๊ต์ฒดํ•˜๊ฑฐ๋‚˜ ์ƒˆ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ฐฐ์—ด์˜ ๋‚ด์šฉ์„ ๋ณ€๊ฒฝํ•œ๋‹ค.

array.splice(start, deleteCount, plusitem);

๐Ÿ”Ž splice() ์—ฐ์Šตํ•ด๋ณด๊ธฐ

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
//['Jan', 'Feb', 'March', 'April', 'June'];

โœ”๏ธ ํ•˜๋‚˜๋„ ์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ , 2๋ฒˆ ์ธ๋ฑ์Šค์— "drum"๊ณผ "guitar" ์ถ”๊ฐ€

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(2,0,'drum','guitar');
//["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]

โœ”๏ธ 3๋ฒˆ ์ธ๋ฑ์Šค์—์„œ ํ•œ ๊ฐœ ์š”์†Œ ์ œ๊ฑฐ

let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
let removed = myFish.splice(3,1);
//["angel", "clown", "drum", "sturgeon"]

โœ”๏ธ 2๋ฒˆ ์ธ๋ฑ์Šค์—์„œ ํ•œ ๊ฐœ ์š”์†Œ ์ œ๊ฑฐํ•˜๊ณ  "trumpet" ์ถ”๊ฐ€

let myFish = ['angel', 'clown', 'drum', 'sturgeon'];
let removed = myFish.splice(2,1,'trumpet');
//["angel", "clown", "trumpet", "sturgeon"]

โœ”๏ธ 0๋ฒˆ ์ธ๋ฑ์Šค์—์„œ ๋‘ ๊ฐœ ์š”์†Œ ์ œ๊ฑฐํ•˜๊ณ  "parrot", "anemone", "blue" ์ถ”๊ฐ€

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(0,2,'parrot', 'anemone', 'blue');
//["parrot", "anemone", "blue", "trumpet", "sturgeon"]

โœ”๏ธ 2๋ฒˆ ์ธ๋ฑ์Šค์—์„œ ๋‘ ๊ฐœ ์š”์†Œ ์ œ๊ฑฐ

let myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
let removed = myFish.splice(2,2);
//["parrot", "anemone", "sturgeon"]

โœ”๏ธ -2๋ฒˆ ์ธ๋ฑ์Šค์—์„œ ํ•œ ๊ฐœ ์š”์†Œ ์ œ๊ฑฐ

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(-2,1);
//["angel", "clown", "sturgeon"]

โœ”๏ธ 2๋ฒˆ ์ธ๋ฑ์Šค๋ฅผ ํฌํ•จํ•ด์„œ ์ดํ›„์˜ ๋ชจ๋“  ์š”์†Œ ์ œ๊ฑฐ

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
let removed = myFish.splice(2);
//["angel", "clown"]
profile
console.log(frontendjigu( โ˜•๏ธ, ๐Ÿ“ฑ); // true

0๊ฐœ์˜ ๋Œ“๊ธ€