본문 바로가기
JS

Slice & Splice

by memory-log 2020. 9. 21.

slice 와 splice 차이 및 사용방법

slice

  • begin 부터 end까지 (end 미포함)
  • end 생략시 : 배열의 끝까지 ( length)
  • 음수 : ex) slice(2, -1) 세번째부터 끝에서 두번째 요소까지
const animals = ["ant", "bison", "camel", "duck", "elephant"]

console.log(animals.slice(2))
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4))
// expected output: Array ["camel", "duck"]

splice

  • 배열의 기존 요소를 삭제 교체 추가
const months = ["Jan", "March", "April", "June"]
months.splice(1, 0, "Feb")
// inserts at index 1
console.log(months)
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, "May")
// replaces 1 element at index 4
console.log(months)
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

'JS' 카테고리의 다른 글

detect iPhone X device with JavaScript  (0) 2020.09.21
replace & replaceAll 문자열 치환하기  (0) 2020.09.21
JS Pattern  (0) 2020.09.21
currentTarget Target 차이  (0) 2020.09.21
JS Map, Filter, Reduce  (0) 2020.09.21

댓글