今天忽然發現這個方法實際上是有問題的。它這個會將'1'和1看作是一樣的,然而實際上它們是不一樣的,咱們簡單的作個小測試.es6
經過下文咱們能夠證實這裏和預想出了誤差,證實了它其實會將'1'和1當作一個東西來判斷。數組
let obj={}; obj[1]=true; console.log(obj['1']); // true
原來的答案(現須要修改)測試
// 數組去重 var array = ['2', '1', '333', '333', '1', 333]; function unique(arr) { var result = []; var object = {}; for (var i = 0; i < arr.length; i++) { if (!object[arr[i]]) { result.push(arr[i]); object[arr[i]] = 1; } } return result; } console.log(unique(array)); // ['2', '1', '333']
修改以後的完美版this
// 數組去重 let arr = [1, 3, 424, '424', 33, 33, '424']; const uniqueArr = (arr) => { let res = []; let obj = {}; arr.forEach(item => { let prefix = typeof item; if (!obj[prefix + item]) { res.push(item); } obj[prefix + item] = true; }); return res; }; console.log(uniqueArr(arr)); // [ 1, 3, 424, '424', 33 ]
注意: Array.prototype.indexOf是ES5的方法(並不一樣於 String 的 indexOf ES3就有),IE8並不支持編碼
let arr = ["a", "b", "a", "b"]; let tem = []; for (let i = 0; i < arr.length; i++) { console.log(tem.indexOf(arr[i])); if (!~tem.indexOf(arr[i])) { tem.push(arr[i]); } } console.log(tem); // ["a","b"]
function minSort(a, b) { return a - b; //這個是從小到大排序 } function maxSort(a, b) { return b - a; //這個是從大到小 } var array = ['223', '2342', '2', '3424', '2']; array.sort(minSort); var tem = [array[0]]; for (var i = 1; i < array.length; i++) { if (array[i] !== array[i - 1]) { tem.push(array[i]); } } console.log(tem);
Array.prototype.indexOf = function(item) { var result = -1, now = null; if (this.length == 0) { return result; } for (var i = 0, len = this.length; i < len; i++) { now = this[i]; if (now == item) { result = i; //返回元素在第幾項的位置 break; } } return result; }; var array = ['23', '1']; console.log(array.indexOf('1')); // 1
var array = ['2', '3', '2', '998', '1000', 'a', 'f', '213', 'f']; var s = new Set(array); console.log(s); Array.prototype.unique = function () { return Array.from(new Set(this)); } var array = ['2', '3', '2', '998', '1000', 'a', 'f', '213', 'f']; console.log(array.unique()); //['2','3']