array的includes那些事

314 阅读1分钟

includes MDN文档

前言

includes用来检测数组中是否存在某值,具体例子可以看MDN文档,基本例子上面都有,不在赘述。

扩展

当我们想检测元素在数组中,会用到includes,然而原生的includes只能检测数字和字符串,对于对象并不能检测会始终反水false,下面是具体的实现,通过下面的例子,就可以检测数组中,对象是否存在。

/**
 * @param arr {Array} 原数组
 * @param val {} 需要检测的值
 * @param key {string} 当存在key,则通过key进行判断,数组中是否存在相同的,否则将进行完全匹配
 * @returns {boolean}
 */
function includes (arr: any[], val: string | number | object, key?: string): boolean {
    if (['string', 'number'].includes(typeof val)) {
        return arr.includes(val)
    }
    if (val instanceof Object) {
        if (key) {
            return arr.some(item => item[key] === val[key])
        } else {
            return arr.some(item => {
                const keys = item instanceof Object ? Object.keys(item) : null
                return keys?.some(keyItem => {
                    return Object.keys(val).every(children => {
                        return item[children] === val[keyItem]
                    })
                })
            })
        }
    }
}

// example
includes([2,4,6,7], 2) // true
includes([
    {
        id: 2,
        every: '3'
    },
    {
        id: 3
    }
], {
    id: 2,
    name: 3
}) // false
includes([
    {
        id: 2,
        three: '3'
    },
    {
        id: 3
    }
], {
    id: 4,
    name: 3
}, 'id') // false