kangduu / front-end-camps

Front-end learning, interviews, question banks, algorithm camps.
https://kangduu.github.io/front-end-camps
MIT License
2 stars 0 forks source link

Q:JavaScript中对比两个数组相等,你有几种方法? #24

Open kangduu opened 9 months ago

en-cheng-river commented 9 months ago

1.循环比较

function arrayIsEqual (arr1, arr2) {
    if(arr1.length !== arr2.length){
        return false
    }
    for (let i = 0;i<arr1.length;i++){
        if(arr1[i] !== arr2[i]) return false
    }
    return  true
}

2. 使用JSON.stringify进行比较(仅限于数据为基本数据的类型)

function arraysAreEqual2 (arr1, arr2) {
    return JSON.stringify(arr1) === JSON.stringify(arr2);
}

3. 使用every方法

function arraysAreEqual3 (arr1, arr2) {
    return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
}