JavaScript implements the method of inserting several elements into an array at a specified location

  • 2020-05-26 07:49:41
  • OfStack

This article demonstrates an example of how JavaScript implements the insertion of several elements into an array at a specified location. Share with you for your reference. The details are as follows:

We can simply insert a new element at the point of execution through the splice method of the JS array


<!DOCTYPE html>
<html>
<body>
<p id="demo">
Click the button to add elements to the array.
</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
</body>
</html>

The output of the above code is as follows:

Banana,Orange,Lemon,Kiwi,Apple,Mango

I hope this article has been helpful to your javascript programming.


Related articles: