关于javascript:loadashjs源码学习笔记2

40次阅读

共计 1353 个字符,预计需要花费 4 分钟才能阅读完成。

集体记忆

lodash.js->Array->difference

用法

返回一个去重后的数组,每个值不蕴含在其余数组参数中。后果值的程序是由第一个数组中的程序确定。

例子

    _.difference([1,2,3],[3],[1,5])
    //==>[2];

源码了解

    difference(array, values, iteratee, comparator) {
      var index = -1,
          includes = arrayIncludes,
          isCommon = true,
          length = array.length,
          result = [],
          valuesLength = values.length;

      if (!length) {return result;}
      if (iteratee) {values = arrayMap(values, baseUnary(iteratee));
      }
      if (comparator) {
        includes = arrayIncludesWith;
        isCommon = false;
      }
      else if (values.length >= LARGE_ARRAY_SIZE) {
        includes = cacheHas;
        isCommon = false;
        values = new SetCache(values);
      }
      outer:
      while (++index < length) {var value = array[index],
            computed = iteratee ? iteratee(value) : value;

        if (isCommon && computed === computed) {
          var valuesIndex = valuesLength;
          while (valuesIndex--) {if (values[valuesIndex] === computed) {continue outer;}
          }
          result.push(value);
        }
        else if (!includes(values, computed, comparator)) {result.push(value);
        }
      }
      return result;
    }


    1. 外围代码
      outer:
      while (++index < length) {var value = array[index],
            computed = iteratee ? iteratee(value) : value;

        if (isCommon && computed === computed) {
          var valuesIndex = valuesLength;
          while (valuesIndex--) {if (values[valuesIndex] === computed) {continue outer;}
          }
          result.push(value);
        }
        else if (!includes(values, computed, comparator)) {result.push(value);
        }
      }
      return result;
      ` 思路:` 将除 array 之外的数组参数合并去重,失去 values, 再应用 includes 办法,判断 array 中的元素是否存在于 values 中,若不存在行将 value 放进新数组 result 中,最初返回 result。

延申

 假如有一需要,重点展现本月在本年没有呈现过的新呈现的天气类型:
difference(month12,month1,month2.....);

正文完
 0