JS中数组去除重复
法一:返回新数组每个位子类型没变
function outRepeat(a){ var hash=[],arr=[]; for (var i = 0; i < a.length; i++) { hash[a[i]]!=null; if(!hash[a[i]]){ arr.push(a[i]); hash[a[i]]=true; } } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"]
法二:类似于法一,但本农觉着法一更易于理解
function outRepeat(a){ var hash=[],arr=[]; for (var i = 0,elem;(elem=a[i])!=null; i++) { if(!hash[elem]){ arr.push(elem); hash[elem]=true; } } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"]
法三:比前两个更易于理解但是返回的新数组每个位子的number类型变为string类型了!!关键时刻得处理
function outRepeat(a){ var hash=[],arr=[]; for (var i = 0; i < a.length; i++) { hash[a[i]]=null; } for(var key in hash){ arr.push(key); } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//["2", "4", "5", "a"]
-----------------------------------------------------------------------小二给我来二两轮子!