前端入门-JS数组-数组去重

106 阅读1分钟

方法1

const arr = [1,2,5,1,2,5,6,1,25]
const res = [...new Set(arr)];

console.log(arr); //  [1, 2, 5, 1, 2, 5, 6, 1, 25]
console.log(res); //  [1, 2, 5, 6, 25]

方法2

const arr = [1,2,5,1,2,5,6,1,25]
const res = [];
res[0] = arr[0];
for(let i = 0; i < arr.length; i++){
    for(let j = 0; j < arr.length; j++){
        if(res[j] === arr[i]){
            break;
        }
        if(j === res.length-1){
            res.push(arr[i]);
        }
    }
}
console.log(arr); //  [1, 2, 5, 1, 2, 5, 6, 1, 25]
console.log(res); //  [1, 2, 5, 6, 25]