对一个数组删除其重复元素,保留删除的元素或者保留删除后的元素皆可。
若借用新的数组变量,则:
Array.prototype.rmRepeat = function() { // body... var newArr = [], rptArr = [], len = this.length; for (var i = 0; i < len; i++) { if (newArr.indexOf(this[i]) == -1) { newArr.push(this[i]); }else{ rptArr.push(this[i]); } }; return newArr; }; [3,2,3,45,44,3,2,1].rmRepeat()
若不能借用新的数组变量,则会复杂一些
Array.prototype.rmrepeat = function() { var len = arr.length; var newarr = []; for (var i = 0; i < len; i++) { var tmp = arr[i]; var j = i+1; while(j < len){ if (arr[j] == tmp) { newarr.push(arr.splice(j,1)) j = j -1; }; j = j + 1; } }; return newarr; }