Javascript Array push() method

Description

Javascript Array push() method



Array.prototype.push = function () {
  for (var i=0; i<arguments.length; i++)
    this[this.length] = arguments[i];
  return this.length;
}

Javascript Array push()

Array.prototype.push = function () {
  var n = this.length
  var m = arguments.length
  for (var i = 0; i < m; i++) {
    this[i + n] = arguments[i]//w  w w .  j  av  a2s  .c  o m
  }
  this.length = n + m
  return this.length
}

var a = [1, 2]
a.push(3, 4)

console.log(a)

Javascript Array push()

var a = ['a', 'b', 'c'];
var b = ['x', 'y', 'z'];
var c = a.push(b, true);
console.log("a : " + a); // a is  ['a', 'b', 'c', ['x', 'y','z'], true]
console.log("c : " + c); // 5

//push can be implemented this way :

Array.prototype.push = function () {
    this.splice.apply(//from w w  w .  j a  v  a2 s. com
        this,
        [this.length, 0].concat(Array.prototype.slice.apply(arguments))
    );

    return this.length;
};

var d = ['a', 'b', 'c'];
var e = ['x', 'y', 'z'];
var f = d.push(e, false);

console.log(d);
console.log(f);



PreviousNext

Related