Javascript Array move(oldIndex, newIndex) method

Description

Javascript Array move(oldIndex, newIndex) method


Array.prototype.move = function(oldIndex, newIndex) {

  if (isNaN(newIndex) || isNaN(oldIndex) || oldIndex < 0 || oldIndex >= this.length) {
    return;//from  w  w  w. ja v  a  2s.  co m
  }

  if (newIndex < 0) {
    newIndex = this.length - 1;
  } else if (newIndex >= this.length) {
    newIndex = 0;
  }

  this.splice(newIndex, 0, this.splice(oldIndex, 1)[0]);

  return newIndex;
};

Javascript Array move(oldIndex, newIndex)

'use strict';/* w w  w  .  jav  a2 s .  co m*/

Array.prototype.move = function (oldIndex, newIndex) {
  if (newIndex >= this.length) {
    var k = newIndex - this.length;
    while ((k--) + 1) {
      this.push(undefined);
    }
  }

  this.splice(newIndex, 0, this.splice(oldIndex, 1)[0]);

  return this; // for testing purposes
};



PreviousNext

Related