题目:请给Array本地对象增加一个原型方法,它用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除的重复条目的新数组。
参考答案1:
Array.prototype.distinct = function() { for(var i = 0; i<this.length; i++){ for(var j = i+1; j<this.length-1;j++){ if(this[i] === this[j] ){ this.splice(j,1); j--; } } } return this; } document.write([1,2,3,1,2,2,2,2,3,3,4,5,6].distinct()) //测试结果为:1,2,3,4,5,6 |
参考答案2:
Array.prototype.uniq = function(){ return [...new Set(this)] } |
参考答案3:
Array.prototype.distinct = function(){ var arr=[]; this.map(function(d){ (arr.indexOf(d)<0) && arr.push(d) }); return arr; }; |
参考答案4:
Array.prototype.distinct = function(){ var arr=[]; this.map(function(d){ if(arr.indexOf(d)<0){ arr.push(d) } }); return arr; }; |