Method to insert elements in front of an JavaScript array

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

This example shows you how to insert elements in front of an JavaScript array. Share with you for your reference. The details are as follows:

The JS array has one unshift method to add several elements to the front of the array. Here is a detailed code demonstration

<!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.unshift("Lemon","Pineapple");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
<p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p>
</body>
</html>

The array will look like this

Lemon,Pineapple,Banana,Orange,Apple,Mango

unshift worked a little badly in ie8 and before. The array inserts elements, but the return value is undefined

I hope this article has helped you with your javascript programming.


Related articles: