【问题标题】:Using lodash _.memoize combine with _.random使用 lodash _.memoize 结合 _.random
【发布时间】:2018-01-24 10:53:45
【问题描述】:

我看到有人(在 angularjs 中)编写了这段代码,我想知道它是如何工作的(只是问我的知识):

    $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
            return !!_.random(0, 4);
        });
    };
    $scope.changeVisibility()

和额外的 HTML 视图(使用了 changeVisibility 和 visibility):

<button ng-click="changeVisibility()">Visibility change</button>
<div class="row">
  <div class="col" visible="visibility(1)">
    1. Row, 1. Col
  </div>

  <div class="col" visible="visibility(2)">
    Mark Hane<br>
    28 yearold<br>
    234 SG
  </div>

  <div class="col" visible="visibility(3)">
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 1. Row --  1<br>
      1. Row, 3. Col, 1. Row --  2
    </div>
    <div class="row"  ng-if="visibility(3)">
      1. Row, 3. Col, 2. Row --  1<br>
      1. Row, 3. Col, 2. Row --  2<br>
      1. Row, 3. Col, 2. Row --  3
    </div>
  </div>
</div>
... so on to  visibility(9)
</div>
</html>

谁能告诉我?非常感谢。

【问题讨论】:

  • 代码的哪一部分看不懂?当你运行代码时发生了什么,什么符合你的期望?您是否尝试在控制台中调用 memoized 函数来探索它的行为方式?

标签: javascript angularjs lodash memoization


【解决方案1】:

如果它在 visibility 函数中滚动 0,我相信它会隐藏一些内容。基本上,它有 1/X 的小概率被隐藏,其中 X 是_.random(0,X) 中的最高范围。它将这个生成的数字存储在 cache 中,用于具有_.memoize 的特定索引(可能是为了减少每个观察者的 $digest 循环可执行文件)。

这是一个类似的代码,看看它是如何工作的 (Plunker):

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<body ng-app="app">
  <div ng-controller="myCtrl">
    <button ng-click="changeVisibility()">Visibility change</button>
    <div ng-repeat="i in [1,2,3,4,5,6,7,8,9,10]">
      visibility({{$index+1}}) - {{visibility($index+1)}}
      <span ng-if="visibility($index+1)">- [i c u]</span>
    </div>
  </div>
  <script>
    var app = angular.module('app', []);
    app.controller('myCtrl', function($scope) {
      $scope.changeVisibility = function() {
        $scope.visibility = _.memoize(function() {
          return !!_.random(0, 10);
        });
      };
      $scope.changeVisibility(); // initialise 
    });
  </script>
</body>

</html>

【讨论】:

  • 和 memoize 返回一个函数接受一个参数,对吧?我没有看到 memoize 的输入函数有参数,你能帮我解释一下吗?
  • @phongly 它returns the new memoizing function。如果你在不带参数的情况下显示{{visibility}},你会看到它是一个有JS的函数argumentsfunction (){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;if(i.has(u))return i.get(u);var o=n.apply(this,e);return r.cache=i.set(u,o)||i,o}
猜你喜欢
  • 2019-03-04
  • 2019-01-16
  • 2017-07-14
  • 2016-11-07
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 2015-12-09
相关资源
最近更新 更多