js基礎演算法--陣列:判斷去重
function mus(nums){ var nary =nums.sort(); console.log(nary); for(var i=0; i<nums.length; i++){ if (nums[i]==nary[i+1]){ return true } else { return false } } } console.log(mus([1,1 ,3,2])); 第二種 var arr =[1,1,2,2,5]; var s =arr.join(',')+","; var arrd=[];console.log(s); for (var i=0; i<arr.length; i++){ if (s.replace(arr[i]+",","").indexOf(arr[i]+",")>-1){ console.log(arr[i]); arrd.push(arr[i]); } } //第三種 var arr =[1,2]; arrRepeat([1,2,2,5,6]) function arrRepeat(arr){ var arrStr =arr.join(',')+","; console.log(arrStr); console.log(arr); for (var i = 0; i < arr.length; i++) { console.log("倒敘:"+arrStr.lastIndexOf(arr[i])); console.log("正數:"+arrStr.indexOf(arr[i])); if (arrStr.indexOf(arr[i]) != arrStr.lastIndexOf(arr[i])){ return true; } } return false; }