非常常用的一段代碼
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());