js实现 find 函数

复制代码
// arr:要查找的数组,predict:要查找的 key 字符串 或 [key,value] 数组,或 对象{key,value},fromIndex:要从数组中第一个元素开始查,默认为 0
function find(arr, predict, fromIndex = 0) {
    // 定义查找元素存在的函数,即当该函数满足条件,则说明可以找到,返回找到的第一个满足条件的对象
    let predictFn = null;
    // 如果 predict 传入的是字符串 key
    if (typeof predict === "string") {
        // 这里传入的 item 相当于遍历 arr 数组 中的某一条数据
        predictFn = (item) => item[predict];
    } else if (Array.isArray(predict)) {
        // 如果传入的是数组 [key,value]
        predictFn = (item) => item[predict[0]] === predict[1];
    } else if (Object.prototype.toString.call(predict) === "[object Object]") {
        // 如果传入的是对象 {key:value,key2:value2}
        let keys = Object.keys(predict);
        predictFn = (item) => {
            return keys.every((key) => item[key] === predict[key]);
        };
    }
    for (let i = fromIndex; i < arr.length; i++) {
        let item = arr[i];
        // 最终判断predictFn这个条件是否满足,满足则返回 item 即满足条件的整条数据
        if (predictFn(item)) {
            return item;
        }
    }
    return undefined;
}
console.log(
    find(
        [
            { a: 1, b: 2, c: 3 },
            { a: 4, b: 5, c: 6, d: 8 },
        ],
        "a"
    )
);
console.log(
    find(
        [
            { a: 1, b: 2, c: 3 },
            { a: 4, b: 5, c: 6, d: 8 },
        ],
        "d"
    )
);
console.log(
    find(
        [
            { a: 1, b: 2, c: 3 },
            { a: 4, b: 5, c: 6, d: 8 },
        ],
        ["a", 4]
    )
);
console.log(
    find(
        [
            { a: 1, b: 2, c: 3 },
            { a: 4, b: 5, c: 6, d: 8 },
        ],
        { a: 4 }
    )
);

// { a: 1, b: 2, c: 3 }
// { a: 4, b: 5, c: 6, d: 8 }
// { a: 4, b: 5, c: 6, d: 8 }
// { a: 4, b: 5, c: 6, d: 8 }
 
复制代码

参考链接:https://www.cnblogs.com/dont27/p/16364633.html

posted @   蓓蕾心晴  阅读(766)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2018-08-22 react给一个div行内加背景图片并实现cover覆盖模式居中显示
2018-08-22 react获取当前页面的url参数
点击右上角即可分享
微信分享提示