Javascript Data Type How to - Get next element in an array








Question

We would like to know how to get next element in an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function getNextMember(array, startIndex) {
   startIndex = startIndex || 0;<!-- w w  w .jav a  2  s .c o  m-->
   return function() {
      startIndex++;  
      return array[startIndex];
   };
};
var word = [
   'is',
   'am',
   'a'
];
var getNextWord = getNextMember(word);
document.writeln(getNextWord );
document.writeln('<br/>');

document.writeln(getNextWord() + ' ' + getNextWord());

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: