一些题目

//扩展Array原型,编写一个去除数组重复项的方法

// 算法一,两层循环,性能差 Array.prototype.unique = function(){ var len = this.length, i; // 两两比较(数组长度大于1) while ( --len > 0 ) { i = len; while ( --i >= 0 ) { // 前一项索引最小为0 if ( this[len] === this[i] ) { // 最后一项与前一项进行比较 //this.splice(i, 1); // this.length自动减一,删除前面的重复项 this.splice(len, 1); // this.length自动减一,删除后面的重复项 i--; } } } return this; }; // 算法二,性能优化 Array.prototype.unique = function(){ var i, key, len = this.length, cache = {}, // 缓存对象 ret = []; // 要返回的数组 for ( i = 0; i < len; i++ ) { key = typeof this[i] + this[i]; if ( cache[key] !== 1 ) { cache[key] = 1; ret.push( this[i] ); } } return ret;; }; // 解决方法三,直接使用jQuery.unique工具函数 var arr = [1,3,4,6,9,10,4,6]; arr = jQuery.unique( arr ); // [1, 3, 4, 6, 9, 10]

  

原文地址:https://www.cnblogs.com/danghuijian/p/3816804.html