You're here: Snippet Directory » HTML/JavaScript (65)
Language:

Array Extensions

Language: English
Programming Language: JavaScript
Published by: pjjt [not registered]
Last Update: 5/15/2006
Views: 1173


Description

Extends the array object. remove, add, swap, pop, min, max, avg.

Code

1 function ExtendArray() { 2 Array.prototype.remove = Array_Remove; 3 Array.prototype.add = Array_Add; 4 Array.prototype.swap = Array_Swap; 5 // removes and returns last element 6 Array.prototype.pop = Array_Pop; 7 // use these with arrays of ints 8 Array.prototype.min = Array_GetMin; 9 Array.prototype.max = Array_GetMax; 10 Array.prototype.avg = Array_GetAvg; 11 } 12 13 14 function Array_Remove(c) { 15 var tmparr = new Array(); 16 for (var i=0; i<this.length; i++) if (i!=c) tmparr[tmparr.length] = this[i]; 17 return tmparr; 18 } 19 20 function Array_Add(c, cont) { 21 var tmparr = new Array(); 22 for (var i=0; i<this.length; i++) { 23 if (i==c) tmparr[tmparr.length] = cont; 24 tmparr[tmparr.length] = this[i]; 25 } 26 if (!tmparr[c]) tmparr[c] = cont; 27 return tmparr; 28 } 29 30 function Array_Swap(x, z) { 31 var zvalue = this[z]; 32 this[z] = this[x]; 33 this[x] = zvalue; 34 return this; 35 } 36 37 function Array_Pop() { 38 var item = this[this.length-1]; 39 this.length--; 40 return item; 41 } 42 43 function Array_GetMin() { 44 var Min = this[0]; 45 if (isNaN(Min*1) && !IsDate(Min)) return ''; 46 for (var i=0; i<this.length; i++) if (this[i]*1<Min) Min = this[i]; 47 return Min; 48 } 49 50 function Array_GetAvg() { 51 var Total = 0; 52 if (isNaN(this[0]*1) && !IsDate(this[0])) return ''; 53 for (var i=0; i<this.length; i++) if (this[i] != 0) Total += this[i]*1; 54 var Avg = Total/(Comps.length+1) 55 if ((Avg+"").indexOf(".") > -1) { 56 if (GetMax(i)-GetMin(i) > 50) Avg = Math.round(Avg); // if difference between min and max > 50, round 57 else Avg = (Avg+"").substring(0,(Avg+"").indexOf(".")+((bFloat) ? 3 : 2)); // else if all values were whole round to 2 places, else 3 58 } 59 return (Avg>0) ? Avg : ""; 60 } 61 62 function Array_GetMax() { 63 var Max = this[0]; 64 if (isNaN(Max*1) && !IsDate(Max)) return ''; 65 for (var i=0; i<this.length; i++) if (this[i]*1>Max) Max = this[i]; 66 return Max; 67 } 68

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS