Array. prototype. unique1 = function (){ Var n = []; // a new temporary Array For (var I = 0; I <this. length; I ++) // traverses the current array { // If the I of the current array has been saved as a temporary array, skip this step, // Otherwise, push the current item to the temporary array. If (n. indexOf (this [I]) =-1) n. push (this [I]); } Return n; }; Array. prototype. unique2 = function () { Var n = {}, r = []; // n is a hash table, and r is a temporary array. For (var I = 0; I <this. length; I ++) // traverses the current array { If (! N [this [I]) // If the hash table does not have the current item { N [this [I] = true; // save it to the hash table R. push (this [I]); // pushes the current item of the current array to the temporary array. } } Return r; }; Array. prototype. unique3 = function () { Var n = [this [0]; // result Array For (var I = 1; I <this. length; I ++) // traverse from the second entry { // If the position where the I entry of the current array appears for the first time in the current array is not I, // This indicates that the I-th item is repeated and ignored. Otherwise, the result array is saved. If (this. indexOf (this [I]) = I) n. push (this [I]); } Return n; }; Array. prototype. unique4 = function () { This. sort (); Var re = [this [0]; For (var I = 1; I <this. length; I ++) { If (this [I]! = Re [re. length-1]) { Re. push (this [I]); } } Return re; }; Var arr = [1, 2, 2, 3, 4, 5]; Console. log (arr. unique1 (); // [1, 2, 3, 4, 5] Console. log (arr. unique2 (); // [1, 2, 3, 4, 5] Console. log (arr. unique3 (); // [1, 2, 3, 4, 5] Console. log (arr. unique4 (); // [1, 2, 3, 4, 5] |