首页 > 解决方案 > 无法理解这些功能

问题描述

//iterator(value, key, collection)
  _.each = function(collection, iterator) { //takes in collection of values and a functino called iterator
    if(Array.isArray(collection)) { //if collection is array, proceed
      for (var key = 0; key < collection.length; key++) { //iterates over the length of collection
        iterator(collection[key], key, collection);//plugs in individual element value, index of element, and array var
      }
    } else {
      for (var objKey in collection) {
        iterator(collection[objKey], objKey, collection);
      }
    }
  };

  _.indexOf = function(array, target){
    var result = -1; //set result to -1

    _.each(array, function(item, index) {
      if (item === target && result === -1) {
        result = index;
      }
    });

    return result;
  };
//example of input
  _.indexOf = function([1, 2, 3], 2)

我无法理解这些函数。特别是在 ._indexOf 变量赋值中使用 _.each 函数的位置。在执行 ._each(array, function(item, index) 的代码行中。该函数的结果是然后用于插入 function(item, index) 的函数还是相反?如何它知道该变量的项目和索引参数是什么?

标签: javascriptfunction

解决方案


推荐阅读