the murmurous sea

JS, ES1: splice() 본문

#dev/개념정리

JS, ES1: splice()

lunacer 2020. 5. 4. 13:17

1. adds/removes items to/from an array, and returns the removed item(s).
   : changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
2. This method changes the original array.

[Syntax]

let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start   The index at which to start changing the array.
Use negative values to specify the position from the end of the array.
If greater than the length of the array,

Start will be set to the length of the array
No element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
If negative It will begin that many elements from the end of the array. 
(In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.)
If array.length + start is less than 0,  It will begin from index 0.
deleteCount Optional An integer indicating the number of elements in the array to remove from start.
If deleteCount is omitted, or All the elements from start to the end of the array will be deleted.
If its value is equal to or larger than array.length - start
If deleteCount is 0 or negative,  No elements are removed.
In this case, you should specify at least one new element.
item1, item2, ...

Optional The new elements to add to the array, beginning from start. 
If you do not specify any elements, splice() will only remove elements from the array.

 

[Return value]

: An array, containing the deleted elements(if any).
: changes the original array.
: If only one element is removed, an array of one element is returned.
: If no elements are removed, an empty array is returned.

 

[Example]

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

// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

https://www.w3schools.com/jsref/jsref_splice.asp

'#dev > 개념정리' 카테고리의 다른 글

DOM: nodeValue vs. textConent vs. innerText vs. innerHTML  (0) 2020.05.04
JS ES1: slice()  (0) 2020.05.04
JS, ES1: split()  (0) 2020.05.04
JS: padStart() & padEnd()  (0) 2020.05.04
[HTML DOM] DocumentFragment  (0) 2020.05.02
Comments