1.循环方法
function methodOne(arr){ var result = [], arrLen = arr.length, item = null, i,j; for(var i = 0; i < arrLen; i++){ //循环数组长度 item = arr[i]; //当前项 var resultLen = result.length; //新建数组长度 for(var j = 0; j < resultLen; j++){ //循环新数组 if(item === result[j]){ //如果当前item等新数组中的其中一个就跳过; break; //停止循环 } } if(j === resultLen){ //如果长度相等就添加当前项 result.push(item); } } return result; }
2.数组的indexOf()方法,需要做IE兼容
function methodTwo(arr){ var result = []; var arrLen = arr.length; var item,i; for(var i = 0; i < arrLen; i++){ item = arr[i]; if(result.indexOf(item) === -1){ //如果不存在就添加 result.push(item); } } return result; } //添加数组IndexOf方法 if (!Array.prototype.indexOf){ Array.prototype.indexOf = function(elt /*, from*/){ var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0){ from += len; } for (; from < len; from++){ if (from in this && this[from] === elt){ return from; } } return -1; }; }
3.ES5方法的forEach()方法
function methodThree(arr){ var result = []; //三个参数:数组元素,元素的索引,数组本身 arr.forEach(function(item,index,array){ //从前面开始查找数组中的元素,如果有重复的,查找的索引与元素索引不相等 if(array.indexOf(item) === index){ result.push(item); } }) return result; }
4.判断类型(能去除个对象组成的数组)
function methodFive(arr){ var result = []; var hash = []; var len = arr.length; for(var i = 0; i < len; i++){ var item = arr[i]; var key; key = typeof(item) + item; //判断类型+值 if(typeof(item) === "object"){ //多个对象时 for(var j in item){ //循环键值对 key = item[j]; //判断类型+值 } } if(hash[key] !== 1){ //如果没有此类型+值,则添加,并将hash[key]赋值为1,如果有重复,下次就有值了 result.push(item); hash[key] = 1; } } return result; }
5.对象的重写覆盖特性(最快的)
Array.prototype.unique = function(){ var obj = {}, len = this.length, result = [], i; for(i = 0; i < len; i++){ var item = this[i]; obj[item] = item; //obj[this[i]]得属性值,如有相同值就会覆盖重写了 } for(i in obj){ result.push(obj[i]); } return result; }
另一种函数定义方法(以上同理)
function eliminateDuplicates(arr){ var i, len = arr.length, result = [], obj = {}; for(var i = 0; i < len; i++){ obj[arr[i]] = 0; } for(i in obj){ result.push(i); } return result; }
测试
var arr1 = [5,7,3,1,7,5,6]; var arr2 = [8,9,5,9,8,3,"3",1]; var arr3 = ["q","b","a","o","q","a"]; var arr4 = ["a","b","c","a","a"]; var arr5 = [{name:"xiaoma"},1,"a",{id:"xl"}]; var arr6 = [{name:"xiaoma"},{name:"xiaoma"}]; var arr7 = [{name:"xiaoma",id:5},{name:"xiaoma2",id:6},{name:"xiaoma3",id:5}]; var arr8 = [true,false,false,true]; var arr9 = [/[d]/,/[w]/]; var arr10 = [/[d]/,/[d]/];