The Wayback Machine - https://web.archive.org/web/20220603125059/https://www.geeksforgeeks.org/javascript-array-splice-method/amp/

JavaScript Array splice() Method

Below is the example of Array splice() method. 

Example: 




<script>
    var webDvlop = ["HTML", "CSS", "JS", "Bootstrap"];
 
    document.write(webDvlop + "<br>");
 
    // Add 'React_Native' and 'Php' after removing 'JS'.
    var removed = webDvlop.splice(2, 1, 'PHP', 'React_Native')
 
    document.write(webDvlop + "<br>");
    document.write(removed + "<br>");
 
    // No Removing only Insertion from 2nd
    // index from the ending
    webDvlop.splice(-2, 0, 'React')
    document.write(webDvlop)
</script>               

Output: 

HTML,CSS,JS,Bootstrap
HTML,CSS,PHP,React_Native,Bootstrap
JS
HTML,CSS,PHP,React,React_Native,Bootstrap

The arr.splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Syntax:  



Array.splice( index, remove_count, item_list )

Parameter: This method accepts many parameters some of them are described below: 

Return Value: While it mutates the original array in-place, still it returns the list of removed items. In case there is no removed array it returns an empty array.

Below example illustrates the Array.splice() method in JavaScript:

Example:  




<script>
var languages = ['C++', 'Java', 'Html', 'Python', 'C'];
 
document.write(languages + "<br>");
 
// Add 'Julia' and 'Php' after removing 'Html'.
var removed = languages.splice(2, 1, 'Julia', 'Php')
 
document.write(languages + "<br>");
document.write(removed + "<br>");
 
// No Removing only Insertion from 2nd index from the ending
languages.splice(-2, 0, 'Pascal')
document.write(languages)
</script>                   

Output: 

C++,Java,Html,Python,C
C++,Java,Julia,Php,Python,C
Html
C++,Java,Julia,Php,Pascal,Python,C 

 Supported Browser:




Article Tags :