extending ecmascript 5 array methods


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



Copy this code and paste it in your HTML
  1. (function(){
  2. var p, ap= Array.prototype,
  3. p2={
  4. filter: function(fun, scope){
  5. var L= this.length, A= [], i= 0, val;
  6. if(typeof fun== 'function'){
  7. while(i< L){
  8. if(i in this){
  9. val= this[i];
  10. if(fun.call(scope, val, i, this)){
  11. A[A.length]= val;
  12. }
  13. }
  14. ++i;
  15. }
  16. }
  17. return A;
  18. },
  19. forEach: function(fun, scope){
  20. var L= this.length, i= 0;
  21. if(typeof fun== 'function'){
  22. while(i< L){
  23. if(i in this){
  24. fun.call(scope, this[i], i, this);
  25. }
  26. ++i;
  27. }
  28. }
  29. return this;
  30. },
  31. every: function(fun, scope){
  32. var L= this.length, i= 0;
  33. if(typeof fun== 'function'){
  34. while(i<L){
  35. if(i in this && !fun.call(scope, this[i], i, this)) return false;
  36. ++i;
  37. }
  38. return true;
  39. }
  40. return null;
  41. },
  42. indexOf: function(what, i){
  43. i= i || 0;
  44. var L= this.length;
  45. while(i< L){
  46. if(this[i]=== what) return i;
  47. ++i;
  48. }
  49. return -1;
  50. },
  51. lastIndexOf: function(what, i){
  52. var L= this.length;
  53. i= i || L-1;
  54. if(isNaN(i) || i>= L) i= L-1;
  55. else if(i< 0) i += L;
  56. while(i> -1){
  57. if(this[i]=== what) return i;
  58. --i;
  59. }
  60. return -1;
  61. },
  62. map: function(fun, scope){
  63. var L= this.length, A= Array(this.length), i= 0, val;
  64. if(typeof fun== 'function'){
  65. while(i< L){
  66. if(i in this){
  67. A[i]= fun.call(scope, this[i], i, this);
  68. }
  69. ++i;
  70. }
  71. return A;
  72. }
  73. },
  74. some: function(fun, scope){
  75. var i= 0, L= this.length;
  76. if(typeof fun== 'function'){
  77. while(i<L){
  78. if(i in this && fun.call(scope, this[i], i, this)) return true;
  79. ++i;
  80. }
  81. return false;
  82. }
  83. }
  84. }
  85. for(p in p2){
  86. if(!ap[p]) ap[p]= p2[p];
  87. }
  88. })();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.