Javascript Array shift() method

Description

Javascript Array shift() method


Array.prototype.shift = function () {
   return this.splice(0, 1)[0];
};

Javascript Array shift()

Array.prototype.shift = function() {
  var elem = this[0];
  for (var i = 0, len = this.length; i < len - 1; i++) {
    this[i] = this[i + 1];//  www  .jav  a  2 s  .  c o m
  }
  delete this[--this.length];
  
  return elem;
};

Javascript Array shift()

Array.prototype.shift = function () {
    var firstUnit = this[0];
    for (var i = 0; i < this.length; i++)
    {//from  www  .  j  a va 2 s. c om
        this[i] = this[i+1];
    }
    this.pop();

    return firstUnit;
}

Javascript Array shift()

//array.shift()/*from   w w  w .  j  a  va  2s . co m*/
var a = ['a', 'b', 'c'];
var c = a.shift(); //
console.log('a : ' + a); // b,c
console.log('c : ' + c); // a

//shift can be implemented like this.
//The splice() method adds/removes items to/from an array, and returns the removed item(s).
//array.splice(start,deleteCount,item..)

Array.prototype.shift = function () {
    return this.splice(0, 1)[0];
};

var d = ['a', 'b', 'c'];
var e = d.shift(); // a
console.log('e : ' + e); // a
console.log('d : ' + d); // a



PreviousNext

Related