javascript用对象方法实现数组去重并排序

时间:2022-07-14 19:04:04
<script>
//用对象方法实现数组去重
Array.prototype.unique = function() {
var newArr = [];
for (var i = 0; i < this.length; i++) {
if(newArr.indexOf(this[i]) == -1){
newArr.push(this[i]);
}
}
return newArr;
};


var jarr = [1,2,4,3,45,6,33,4,2];
var unq = jarr.unique();
console.log(unq);

//对结果排序 sort
unq.sort(function compare(a,b){
return a-b; //倒序 b-a
});
console.log(unq);

</script>