unshift()

Started by beingchinmay, 09-23-2016, 06:11:39

Previous topic - Next topic

beingchinmayTopic starter

The unshift() method is the opposite of the shift() method. It appends a list of elements to the beginning of an array. Here is the method defined as a
prototype of the Array object type, along with an example to demonstrate it:


function unshift()
{
for (var i = 0; i < unshift.arguments.length; ++i)
{
if (unshift.arguments[i] == null)
break
}
// i = number of arguments! (remember ++i is executed during last loop)
// i holds the number of arguments
for (var j = this.length – 1; j >= 0; --j)
{
this[j + i] = this[j]
}
// j == –1
// i == number of arguments
for (j = 0; j < i; ++j)
{
this[j] = unshift.arguments[j]
}
}
Array.prototype.unshift = unshift


Here is an example of the unshift() function:

var line = new Array("ccc", "ddd", "eee")
line.unshift("aaa", "bbb")
document.write(line.join(" "))