① array数组去重
var arr1 = [1,5,5,6,8,8,9];
function unique (array) {
var arr2 = [];
for(var i = 0;i < arr1.length;i++){
if(arr2.indexOf(arr1[i]) == -1){
arr2.push(arr1[i]);
}
}
return arr2;
}
console.log(unique(arr1)); //[1, 5, 6, 8, 9]
② array以原生链的方式数组去重,按从小到大排序
var arr1 = [5,5,1,8,8,6,9];
Array.prototype.unique = function () {
this.sort();
var arr2 = [this[0]];
for(var i=1;i<this.length;i++){
if(this[i] !== arr2[arr2.length-1]){
arr2.push(this[i]);
}
}
return arr2;
}
console.log(arr1.unique()); //[1, 5, 6, 8, 9]
原文地址:https://www.cnblogs.com/wuzhendong/p/8124334.html
时间: 2024-11-05 18:59:32