很容易给出的方案是:
function arrayUnique(target) { var result = [target[0]]; var temp = {}; temp[target[0]] = true; for (var i = 1, len = target.length; i < len; i++) { if(temp[target[i]] === undefined) { result.push(target[i]); temp[target[i]] = true; } } return result;}arrayUnique([1, 2, 3, 4]); // [1, 2, 3, 4]arrayUnique([1, 2, 3, 4, '1']); // [1, 2, 3, 4]
当给定数组变成[1, 2, 3, 4, '1']时,发现结果依然还是 [1, 2, 3, 4],而实际上我们期待的结果应该是[1, 2, 3, 4, '1']。
原因很简单,Object 会将属性的 key 值都转成 String 类型,比如,
var a = {1: 3, '3': 9}Object.getOwnPropertyNames(a) // ["1", "3"]
上述例子中,两个 key 值都被转换成了字符串,再看一下下面一个例子:
var a = { 1: 3, '3': 9}Object.prototype.toString = function() { return 3;}console.log(a[{k: 1}]); // 9
当 key 值是一个object 的时候, 会先调用 toString 将该 object 转成 字符串,再查找。
为了解决这个问题,遍历数组元素,与已保存的元素对比的时候还应该考虑元素的类型,如下:
function arrayUnique(target) { var result = [target[0]]; var temp = {}; temp[target[0]] = {}; temp[target[0]][(typeof target[0])] = 1; for (var i = 1, targetLen = target.length; i < targetLen; i++) { console.log(temp[target[i]], typeof target[i], temp[target[i]][typeof target[i]]); if(temp[target[i]] && temp[target[i]][typeof target[i]] === 1) { continue; } result.push(target[i]); if(typeof temp[target[i]] === 'undefined') { temp[target[i]] = {}; temp[target[i]][typeof target[i]] = 1; } else { temp[target[i]][typeof target[i]] = 1; } } return result;}arrayUnique([1, '1', 1, 5, '5'); // [1, '1', 5, '5']
这样就得到了我们想要的结果。有人会考虑temp对象自带了一个__proto__和length属性,可能在比较中会对结果造成影响。但在测试中,这两个属性只能通过点方法获取,比如temp.__proto__, temp.length,而我们实际比较中使用的是方括号,并不能获取到这两个属性。所以貌似不用太担心,但小心为上,还是使用了Object.create(null),使对象尽可能的纯粹。
function arrayUnique(target) { var result = [target[0]]; var temp = Object.create(null); temp[target[0]] = Object.create(null); temp[target[0]][(typeof target[0])] = 1; for (var i = 1, targetLen = target.length; i < targetLen; i++) { console.log(temp[target[i]], typeof target[i], temp[target[i]][typeof target[i]]); if(temp[target[i]] && temp[target[i]][typeof target[i]] === 1) { continue; } result.push(target[i]); if(typeof temp[target[i]] === 'undefined') { temp[target[i]] = Object.create(null); temp[target[i]][typeof target[i]] = 1; } else { temp[target[i]][typeof target[i]] = 1; } } return result;}