functionunique(arr) { var result = []; for (var i = 0, arrLen = arr.length; i < arrLen; i++) { for (var j = 0, resLen = result.length; j < resLen; j++) { if (arr[i] === result[j]) { break; } } if (j === result.length) { result.push(arr[i]); } } return result; }
第二种:
1 2 3 4 5 6 7 8 9 10 11 12 13
functionunique(arr) { let arrary = [].concat(arr); // 避免修改原数组,存个副本 for (let i = 0, len = arrary.length; i < len; i++) { for (let j = i + 1; j < len; j++) { if (arrary[i] === arrary[j]) { arrary.splice(j, 1); // splice() 修改原数组,所以需要手动修改长度 len--; j--; } } } return arrary; }
indexOf 方法
1 2 3 4 5 6 7 8 9 10
functionunique(arr) { const result = []; for (let i = 0, len = arr.length; i < len; i++) { const current = arr[i]; if (result.indexOf(current) === -1) { result.push(current); } } return result; }
filter + indexOf 方法
1 2 3 4 5 6 7 8 9 10
functionunique(arr) { let result = arr.filter(function(item, index, arr) { return arr.indexOf(item) === index; }); return result; }