【已解决】JavaScript 中数组去重的 3 种方法

方法1:

  使用 Array.from() + set 数据结构

let arr = [1, 3, 3, 5];
 
// 方法1
// Array.from(): 将其他对象转化为数组
// set数据结构:ES6,类似于数组,但其成员值都是唯一的
 
let method1 = array => Array.from(new Set(array));
console.log(method1(arr)); // [1,3,5]

方法2

 使用扩展运算符(...)+ set数据结构

const method2= arr => [...new Set(arr)];
console.log(method2(arr)); // [1,3,5]

方法3

  传统的 for 循环 + 箭头函数

let method3 = array => {
    let newArr = [];
    for(let i = 0; i < array.length; i++){
        if(!newArr.includes(array[i])){
            newArr.push(array[i]);
        }
    }
    return newArr;
}
console.log(method3(arr)); // [1,3,5]

猜你喜欢

转载自blog.csdn.net/Ja_time/article/details/90052464