Javascript Splice Function

JavaScript

JavaScript Splice function is use to add and remove the elements in the Javascript Array.

In order to remove elements first parameter in splice is the position and second parameter is the number of elements to remove.

Example #1:

<!DOCTYPE html>   
<html>   
<body>   
<p id="splice"></p>   
<script>   
var array = ["Java", "Node", "PHP", "Python", "Mongo"];
array.splice(2,2);
document.getElementById("splice").innerHTML = array;
</script> 
</body> 
</html>

Output:

Java

In addition to Splice,To add elements in the Javascript array, first parameter of the splice locate the position.

Second parameter is number of elements to remove after starting position and further parameter are the elements which will be include in the Javascript array

Example #2:

<!DOCTYPE html>   
<html>   
<body>   
<p id="splice"></p>   
<script>   
var array = ["Java", "Node", "PHP", "Python", "Mongo"];
array.splice(2,2,"C#","C++");
document.getElementById("splice").innerHTML = array;
</script> 
</body> 
</html>

Output:

java

Example #3:

<!DOCTYPE html>   
<html>   
<body>   
<p id="splice"></p>   
<script>   
var array = ["Java", "Node", "PHP", "Python", "Mongo"];
array.splice(2,0,"C#","C++");
document.getElementById("splice").innerHTML = array;
</script> 
</body> 
</html>

Output:

java

When we put negative integer in the first parameter than the position element will starting counting from the last to starting of JavaScript array like [“Node“,”Python“,”C++“,”C#“] ,the position of “C++” is both 2 and –1 .

Therefore second parameter will always indicate the number of elements to remove and then furthermore parameter are the values to insert in the JavaScript array

Example #3:

<!DOCTYPE html>    
<html>    
<body>    
<p id="splice"></p>    
<script>    
var array = ["Java", "Node", "PHP", "Python", "Mongo"]; 
array.splice(-2,2); 
document.getElementById("splice").innerHTML = array; 
</script>  
</body>  
</html>

Output:

Java

JavaScript splice function is also remove or add the two dimension array to JavaScript array.

Therefore purpose of all the parameters of will remain the same as in above examples just in third and after third parameter two dimension array is placed.

Example #4:

<!DOCTYPE html>    
<html>    
<body>    
<p id="splice"></p>    
<script> 
var array = ["Java", "Node", "PHP", [4,5,6], "Mongo"]; array.splice(-2,2,[1,2,3,4]); document.getElementById("splice").innerHTML = array; </script> </body> </html>

Output:

java
For more Examples Related CSS,html and Java Script Visit on Coding Academics.
For Web,Java and Assembly language related Semester Projects please Visit on Raheel Tech

Leave a Reply

Your email address will not be published. Required fields are marked *