lodash中findKey的算法

algorithm of findKey in lodash

我想通过对象中的值来查找键,我发现 lodash 为我们提供了方便 api findKey 可以帮助我。

但我的问题是,findKey 是如何工作的?这与 hash 普通键值映射不同吗?

我对此一无所知,如果可以的话,你能提供一些例子来比较一下吗?

感谢您的宝贵时间!

Lodash 是一个开源库,您可以检查其源代码以检查其所有功能的实现。

https://github.com/lodash/lodash/blob/master/lodash.js

findKey 大概可以追溯到第 716 行的 baseFindKey 函数:

function baseFindKey(collection, predicate, eachFunc) {
  var result;
  eachFunc(collection, function(value, key, collection) {
    if (predicate(value, key, collection)) {
      result = key;
      return false;
    }
  });
  return result;
}

它的作用是 运行 遍历集合,并且对于集合中的每个成员,运行 谓词检查成员是否与谓词匹配。

如果匹配,则密钥将作为结果返回。