数组去重--ES5和ES6
思路:把去重后的数组放到一个空数组中
ES5实现:
function uni(arr) { var result = []; for (var i=0;i<arr.length;i++) { if(result.indexOf(arr[i])==-1) { result.push(arr[i]); } } return result; } var obj = new uni([1,1,1,1,3,4,5]); console.log(obj);
ES6实现:
function removal(arr) { return Array.from(new Set(arr)); } var obj = new removal([1,2,3,3,3,3,8,6,4,3]); console.log(obj);
在此基础上,要求合并数组并去重也很简单了
Es5:
let arr1 = [1,2,3,4] let arr2 = [3,4,5,6] function uni(arr1,arr2) { var arr3 = arr1.concat(arr2) var arr4 = [] var len = arr3.length for(var i=0;i<len;i++) { if (arr4.indexOf(arr3[i]) === -1) { arr4.push(arr3[i]) } }return arr4 } console.log(uni(arr1,arr2))
Es6:
let arr1 = [1,2,3,4] let arr2 = [3,4,5,6] function uni(arr1,arr2){ arr1.push(...arr2) let arr3 = Array.from(new Set(arr1)) console.log(arr3) } uni(arr1,arr2)