Javascript Array newUnshift(item)

Description

Javascript Array newUnshift(item)


Array.prototype.newUnshift = function (item) {
  var res = [];/*from  ww w.j  a  va2 s .  com*/
  for (let i = 0; i < this.length; i++) {
    if (i == 0) {
      res[i] = item;
    } else {
      res[i] = this[i - 1];
    }
  }
  return res;
}

Javascript Array newUnshift(item)

Array.prototype.newUnshift = function (item) {
  var arr = [item].concat(this);
  return arr;/*from  ww w.j  a  v a 2s  .  c o  m*/
}

Javascript Array newUnshift(item)

Array.prototype.newUnshift = function (item) {
  this.splice(0, 0, item);//  w  w  w  .  ja  v  a 2  s  .  c om
  return this;
}

var a = [1, 2, 3];
var b = a.newUnshift(0);
console.log(b);



PreviousNext

Related