Skip to content

hasIntersection

判断两个数组(简单类型数组)是否有交集

配置项

参数类型是否必选默认值参数描述
array1Array-参数1
array2Array-参数2

返回值

类型描述
Boolean是否有交集

示例

hasIntersection([1], [1,2]) // true
hasIntersection([1], [2]) // false

源码

js
export function hasIntersection(array1, array2) {
    // 检查输入的 array 是否为数组
    if (!Array.isArray(array1) || !Array.isArray(array2)) {
        throw new Error('参数必须是数组');
    }
    const shorter = array1.length < array2.length ? array1 : array2;
    const longer = array1.length < array2.length ? array2 : array1;
    const set = new Set(longer);
    for (let i = 0; i < shorter.length; i++) {
        if (set.has(shorter[i])) {
            return true;
        }
    }
    return false;
}