Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1731 Is there a way of shifting the contents of an array down / up e.g. 1 becomes 2, 2 becomes 3 etc?

You are here: irt.org | FAQ | JavaScript | Object | Q1731 [ previous next ]

Try:

<html>

<head>

<script language="JavaScript"><!--
var numbers = new Array(
  'one','two','three','four','five',
  'six','seven','eight','nine','ten',
  'eleven','twelve','thirteen','fourteen','fifthteen',
  'sixteen','seventeen','eighteen','nineteen'
);

function insertIntoArray(arrayName,position,value) {
  if (position > arrayName.length) position = arrayName.length;

  var copy = new Array();

  for (var i = 0, j = 0; i<arrayName.length; i++) {
    if (j == position) copy[j++] = value;
    copy[j++] = arrayName[i];
  }
  if (j == position) copy[j++] = value;

  return copy;
}

function displayArray(arrayName) {
  var output = '';
  for (var i=0; i<arrayName.length; i++) {
    output += arrayName[i] + '<br>';
  }

  return output;
}
//--></script>

</head>

<body>

<script language="JavaScript"><!--
document.write(displayArray(numbers));
//--></script>

<hr>

<script language="JavaScript"><!--
numbers = insertIntoArray(numbers, 0, '#zero#');
numbers = insertIntoArray(numbers, 21, '#twenty#');

document.write(displayArray(numbers));
//--></script>

</body>

</html>

©2018 Martin Webb