非常常用的一段代码
1 //数组移除指定对象或下标i 2 Array.prototype.remove = function (obj) { 3 for (var i = 0; i < this.length; i++) { 4 var temp = this[i]; 5 if (!isNaN(obj)) { 6 temp = i; 7 } 8 if (temp == obj) { 9 for (var j = i; j < this.length; j++) { 10 this[j] = this[j + 1]; 11 } 12 this.length = this.length - 1; 13 } 14 } 15 }
js 数组去重
//js 数组去重
1 var arr = [1,2,3,4,1,2,4,5,6]; 2 console.log(arr); 3 Array.prototype.unique = function() { 4 var n = []; //一个新的临时数组 5 for (var i = 0; i < this.length; i++) //遍历当前数组 6 { 7 //如果当前数组的第i已经保存进了临时数组,那么跳过, 8 //否则把当前项push到临时数组里面 9 if (n.indexOf(this[i]) == -1) n.push(this[i]); 10 } 11 return n; 12 }; 13 console.log(arr.unique());