switch elements index


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. Array.prototype.switchus = function(a,b) {
  2. var x, y;
  3. for(var i = 0; i < this.length; i++) {
  4. if(a == this[i]) {
  5. x = i;
  6. }
  7. if(b == this[i]) {
  8. y = i;
  9. }
  10. }
  11. if(x && y) {
  12. this[x] = b;
  13. this[y] = a;
  14. return true;
  15. } else {
  16. return false;
  17. }
  18. }
  19.  
  20. var a = [2,3,4,5,'ultimo elemento', 'mesmo'];
  21. result = a.switchus(4,'mesmo');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.