Ryu.log

Array.prototype.splice() 본문

Prev-content

Array.prototype.splice()

류뚝딱 2018. 11. 13. 16:25

Array.prototype.splice()

Array.prototype.splice() 메서드는 배열내 요소를 삭제, 추가, 변경이 자유롭게 가능하다.
let months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

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

array.splice(시작, 삭제여부, [아이템1, 아이템2, 아이템3 ...]); // 시작 : 배열내 변경할 요소의 인덱스 // 삭제 개수 : 배열에서 제거할 요소의 수, 만약 0개면 아무런 요소도 제거되지 않음 // 아이템N : 추가 및 변경될 요소 만약 선언하지 않으면 splice()는 삭제만 함

반환값

추가, 삭제, 변경된 배열이 리턴 된다. 만약 아무런 요소도 삭제되지 않았을 경우에는 빈 배열이 리턴된다.

예제코드

let myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
let removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']




Comments