๐ŸSlice vs Splice vs Split์˜ ์ฐจ์ด์ 

chloeยท2020๋…„ 10์›” 2์ผ
2

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
9/81
post-thumbnail

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ๊ณต๋ถ€ํ•˜๋‹ค๊ฐ€ slice,splice,split์˜ ์ฐจ์ด๊ฐ€ ๋„ˆ~๋ฌด ํ—ท๊ฐˆ๋ฆฌ๋Š” ๊ฒƒ์ด๋‹ค. ์˜์–ด๋‹จ์–ด๋„ ๋น„์Šทํ•˜๊ฒŒ ์ƒ๊ฒจ๊ฐ€์ง€๊ทœ..๐Ÿ˜ญ
๊ทธ๋ž˜์„œ ์ด๋ฒˆ์— ์ •๋ฆฌํ•ด์„œ ๋จธ๋ฆฟ์†์— ์ง‘์–ด ๋„ฃ์–ด์•ผ๊ฒ ๋‹ค~~!! ์˜ค๋Š˜์€ ์ธ๋„ ๊ฐœ๋ฐœ์ž์˜ ๋„์›€์„ ๋ฐ›์•˜๋‹ค! ๊ธ€๋กœ๋ฒŒํ•œ ๊ฐœ๋ฐœ์ž ์„ธ๊ณ„><

์šฐ์„  method type์œผ๋กœ ์ด ์…‹์„ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ๋‹ค.

Array method: Slice() and Splice()
String method: Split()

Slice()

slice()๋Š” ๋ฐฐ์—ด ๋ฉ”์„œ๋“œ๋กœ ์›ํ•˜๋Š” ๋ถ€๋ถ„์„ ๋ณต์‚ฌํ•˜๊ณ  ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฆฌํ„ดํ•œ๋‹ค.
๋ฐฐ์—ด์„ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ํ•ต์‹ฌ์ด๋‹ค.
์•„๋ž˜ ์˜ˆ์‹œ๋ฅผ ์‚ดํŽด๋ณด์ž.

//loaf3๊ณผ loaf5๋ฅผ ์ƒˆ ๋ฐฐ์—ด์— ๋ณต์‚ฌํ•˜๊ณ  ์‹ถ์–ด์šง..

let bread=['loaf1','loaf2','loaf3','loaf4','loaf5','loaf6'];
newArr=bread.slice(2,5);
//output:["loaf3", "loaf4", "loaf5"]

Splice()

Splice() ๋˜ํ•œ ๋ฐฐ์—ด ๋ฉ”์„œ๋“œ๋กœ ๋ฐฐ์—ด์— ์›ํ•˜๋Š” ์—˜๋ฆฌ๋จผํŠธ ๊ฐฏ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋Š” ๊ธฐ์กด ๋ฐฐ์—ด์— ๋ณ€์ด๋ฅผ ์ค€๋‹ค.

  1. ์ œ๊ฑฐ๋งŒ ํ•  ๊ฒฝ์šฐ
let bread = ['loaf1','loaf2','loaf3','loaf4','loaf5','loaf6'];
bread.splice(1, 3);
["loaf2", "loaf3", "loaf4"]
//output:["loaf1", "loaf5", "loaf6"]

2.์ œ๊ฑฐํ•˜๊ณ  ์ƒˆ๋กœ์šด ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒฝ์šฐ

let bread = ['loaf1','loaf2','loaf3','loaf4','loaf5','loaf6'];
bread.splice(1, 3, 'newLoaf1', 'newLoaf2');
console.log(bread);
//output:["loaf1", "newLoaf1", "newLoaf2", "loaf5", "loaf6"]

3.์ถ”๊ฐ€๋งŒ ํ•˜๋Š” ๊ฒฝ์šฐ

let bread = ['loaf1','loaf2','loaf3','loaf4','loaf5','loaf6'];
bread.splice(3, 0, 'newLoaf1', 'newLoaf2');
console.log(bread);
//output:["loaf1", "loaf2", "loaf3", "newLoaf1", "newLoaf2", "loaf4", "loaf5", "loaf6"]

Split()

Split()์€ string ๋ฉ”์„œ๋“œ์ง€๋งŒ ๋ฐฐ์—ด์„ ๋ฆฌํ„ดํ•œ๋‹ค. ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ์ „ํ™˜ํ•  ๋•Œ ๋งค์šฐ ์œ ์šฉํ•˜๋‹ค.
์˜ˆ์‹œ๋ฅผ ์‚ดํŽด๋ณด์žฅ!

let myString = "the quick brown fox jumps over the lazy dog";
//For a comma separated array use " ":
myString.split(" ");
//output: ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
//For each alphabet as element of array use "":
myString.split("");
//output: ["t", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "t", "h", "e", " ", "l", "a", "z", "y", " ", "d", "o", "g"]

๐Ÿ’– ์•Œ์•„๋‘๋ฉด ์ข‹์€ ํŒ

  1. ๋ฐฐ์—ด์— split()์„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด .toString()์„ ์‚ฌ์šฉํ•˜์—ฌ string์œผ๋กœ ์ „ํ™˜ํ•ด๋ผ.
var myString = array.toString();

2.string์„ ๋ฐฐ์—ด๋กœ ์ „ํ™˜ํ•˜๊ธฐ์œ„ํ•ด ("")์™€ ํ•จ๊ป˜ split์„ ์‚ฌ์šฉํ•ด๋ผ

myString.split(" ");

๊ฒฐ๋ก 
๋งŽ์ด ์จ๋ด์•ผ ๋‹ค์‹œ ํ™•์‹คํ•˜๊ฒŒ ์ฐจ์ด์ ์„ ์ตํž ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค!
์ •๋ฆฌ๋ฅผ ํ•˜๋‹ˆ๊นŒ ๋” ์ดํ•ด๊ฐ€ ๋˜๋Š”๊ตฐ~!

์ฐธ๊ณ :https://medium.com/@anupamroy8/slice-vs-splice-vs-split-in-javascript-344c41cb94a5

profile
Front-end Developer ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป

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