数组去重

来源:互联网 发布:keil优化等级设置 编辑:程序博客网 时间:2024/05/29 11:47

/*//1.常规的方法

var arr = [1,2,31,1,1,,4];//在数组原型上绑定方法Array.prototype.unique = function() {    //提出数组中一个值    var res = [this[0]];    //遍历数组    for(var i = 1; i < this.length; i++) {        //做个标记        var repeat = false;        //遍历空数组,并有重复数据时将开关关掉        for( var j = 0; j < res.length; j++) {            if(this[i] == res[j]) {                repeat = true;                break;            }        }        if(!repeat) {            res.push(this[i]);        }    }    return res;}alert(arr.unique());*/var arr = [1,3,1,31,1];//2.先把原数组排序,这样重复的数值会相邻,再将数组中前后两项进行对比/*Array.prototype.unique = function() {    this.sort();    var res = [this[0]];    //数组前后两项对比    for(var i = 0;i < this.length; i++){        if(this[i] != res[res.length - 1]) {            res.push(this[i]);        }    }    return res;}alert(arr.unique());*///3.放入对象的属性中.利用空对象的属性判断代替了第一种方法中的开关/*Array.prototype.unique = function() {    var res = [];    var obj = {};    for(var i = 0; i< this.length; i++) {        if(!obj[this[i]]) {            res.push(this[i]);            obj[this[i]] = 1;        }    }    return res;}alert(arr.unique());*///4.// ES6/*function unique (arr) {  const seen = new Map()  return arr.filter((a) => !seen.has(a) && seen.set(a, 1))}// orfunction unique (arr) {  return Array.from(new Set(arr))}*///5. ES6新方法console.log(Array.from(new Set(arr)));//6. 使用indexOf方法
0 0
原创粉丝点击