Skip to content

Instantly share code, notes, and snippets.

@ShivrajRath
Created January 14, 2015 20:10
Show Gist options
  • Save ShivrajRath/4b5237a6ef2dbf5ca7a3 to your computer and use it in GitHub Desktop.
Save ShivrajRath/4b5237a6ef2dbf5ca7a3 to your computer and use it in GitHub Desktop.
Array Iterator in Javascript
/*************************************************************
* Adds iterator to javascript Arrays
*************************************************************/
/**
* Returns previous element in the iteration
* @return {[object]} [Returns null if iteration has not started or if limit has reached]
*/
Array.prototype.prev = function(){
if(isNaN(this.index) || this.index <=0){
return null;
}
return this[--this.index];
}
/**
* Returns next element in the iteration
* @return {[object]} [Returns null if iteration limit been has reached]
*/
Array.prototype.next = function(){
if(isNaN(this.index)){
this.index = 0;
}
if(this.index >= this.length){
return null;
}
return this[this.index++];
}
/**
* Returns whether or not the iteration has more elements
* @return {[boolean]} [Returns true if the iteration has more elements]
*/
Array.prototype.hasNext = function(){
if(this.index < this.length){
return true;
}
return false;
}
@fdenzer
Copy link

fdenzer commented Sep 19, 2020

doesn't iteration over key in any array instance now print hasNext, next, and prev as three always-present keys? Seems dangerous.
minimal example: https://gist.github.com/endel/4136334

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment