<script type="text/javascript" charset="utf-8" async defer> var arr = [2,1,2,10,2,3,4,1,85,321,3,4,65,10,24]; function uniq(newarr){ function toObject(arr) { var obj = { }; for(var i=0 ;i<arr.length ;i++){ obj[ arr[ i ] ]=true; } return obj ; } function keys(obj){ var arr = [ ] ; for(var attr in obj){ if(obj.hasOwnProperty(attr)){ arr.push(parseInt(attr)); } } return arr; } return keys(toObject(newarr)); } console.log(uniq(arr));
1 回答
李晓健
TA贡献1036条经验 获得超461个赞
没发现你那个哪里不一样呀,你可以试一下其他的方法,比喻先排序,然后把相邻相同的都去掉
<script> var arr = [2,1,2,10,2,3,4,1,85,321,3,4,65,10,24]; var newArray = arr.sort(function(a,b){return a-b;}); var arr2=[]; arr2.push(newArray[0]); for(var i=0;i<newArray.length-1;i++){ if(newArray[i] !== newArray[i+1]){ arr2.push(newArray[i+1]) } } console.log(arr2); </script>
添加回答
举报
0/150
提交
取消