The Javascript array unshift()
method
adds new items to the beginning of an array, and returns its new length.
We can use the push()
method to add new items to the end of an array.
The unshift() method returns undefined in Internet Explorer 8 and earlier versions.
unshift() |
Yes | Yes | Yes | Yes | Yes |
array.unshift(item1,item2, ..., itemX);
item1,item2, ..., itemX
are the items to add to the beginning of the array.
A Number, representing the new length of the array.
var colors = new Array(); //create an array
//from ww w . ja v a 2s. c o m
var count = colors.unshift("A", "B"); //push two items
console.log(count); //2
count = colors.unshift("C"); //push another item on
console.log(count); //3
var item = colors.pop(); //get the first item
console.log(item); //"B"
console.log(colors.length); //2
The code above generates the following result.
The following code shows how to add new items to the beginning of an array:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
var array1 = ["A", "B", "C", "D"];
document.getElementById("demo").innerHTML = array1;
<!--from w w w . jav a2 s.c o m-->
function myFunction() {
array1.unshift("E", "F");
document.getElementById("demo").innerHTML = array1;
}
</script>
</body>
</html>
The code above is rendered as follows: