JavaScript - 编写 indexOf 和 each

JavaScript - Writing indexOf and each

我正在尝试重写 _.each 和 _.indexOf,它让我陷入困境。

我的每个函数接受一个对象或一个数组并通过测试设置。

_['each'] = function(collection, iterator) {
if (Array.isArray(collection) === false && typeof(collection) === 'object') {
  var values = Object.values(collection);
  var keys = Object.keys(collection);
  for (let i = 0; i < values.length; i++) {
    iterator(values[i], keys[i], collection, i);
  }
} else {
  for (let i = 0; i < collection.length; i++) {
    iterator(collection[i], i, collection);
    }
  }
}

所以我假设这段代码没问题,因为它通过了预设测试,但我什至不确定。我的问题是,我将如何编写也使用 each() 函数的 indexOf() 函数?每个都会 运行 每个元素的函数并且不会中断,对吗?而且我无法通过 collection[i] 访问索引,因为 i 在 indexOf 的范围内未定义。我错过了什么?

伪代码,检查是否需要完整的javascript代码:

indexOf = function(element, array){

    // found index
    index = -1;


    // for each element, compare element, store index if found
    each array (function(e, i){

          // use cmp function to deep compare object/array as values
          if(e === element)
          {
              // remove condition for lastIndexOf
              if(index == -1)
              {
                 index = i;
              }
          }

    });

    // return found index
    return index;

}