JavaScript数组去重的多种方法

在JavaScript开发中,数组去重是一个常见的需求。本文将介绍几种实用的数组去重方法。

方法一:使用Set(ES6)
function uniqueArray1(arr) {
    return [...new Set(arr)];
}

const numbers = [1, 2, 2, 3, 4, 4, 5];
console.log(uniqueArray1(numbers)); // [1, 2, 3, 4, 5]
方法二:使用filter和indexOf
function uniqueArray2(arr) {
    return arr.filter((item, index) => {
        return arr.indexOf(item) === index;
    });
}

const fruits = ['apple', 'banana', 'apple', 'orange'];
console.log(uniqueArray2(fruits)); // ['apple', 'banana', 'orange']

Promise的链式调用与错误处理

Promise是JavaScript中处理异步操作的重要工具,掌握其链式调用和错误处理技巧至关重要。

Promise链式调用示例
function fetchUserData(userId) {
    return fetch(`/api/users/${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('用户数据获取失败');
            }
            return response.json();
        })
        .then(user => {
            return fetch(`/api/posts?userId=${user.id}`);
        })
        .then(posts => {
            console.log('用户文章:', posts);
            return posts;
        })
        .catch(error => {
            console.error('发生错误:', error);
            throw error;
        });
}