Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created December 14, 2011 12:12
Show Gist options
  • Select an option

  • Save thinkphp/1476358 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/1476358 to your computer and use it in GitHub Desktop.
Array.prototype.reverse 3 methods
Array.prototype.reverse1 = function() {
var stack = [],
n = this.length
for(var i=n-1;i>=0;i--) {
stack.push(this[i])
}
return stack
}
Array.prototype.reverse2 = function() {
var i = 0,
n = this.length,
j = n - 1;
while(i<j) {
aux = arr[i]
arr[i] = arr[j]
arr[j] = aux
i++;j--;
}
return this
}
Array.prototype.reverse3 = function() {
var middle = this.length/2,
n = this.length-1
for(var i=0;i<middle;i++) {
aux = this[i]
this[i] = this[n-i]
this[n-i] = aux
}
return this
}
var arr = [1,2,3,4,5,6,7,8,9,-1,-2]
console.log(arr.reverse3())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment