【问题标题】:Nested loop breaking嵌套循环中断
【发布时间】:2015-09-11 17:01:09
【问题描述】:

有以下 Angular/CoffeeScript 函数:

User.prototype.hasPermissions = ->
  result = false
  angular.forEach this.scopes, (scope) ->
    angular.forEach scope, (permission) ->
      result = true if permission
  result

它工作得很好,但是这个函数有一些开销——它会一直工作到最后一项。但是当嵌套循环(用于权限)找到第一个“真”值时,我需要从 hasPermissions 返回;尽管此函数必须返回 false。我尝试执行以下操作:

User.prototype.hasPermissions = ->
  angular.forEach this.scopes, (scope) ->
    angular.forEach scope, (permission) ->
      return true if permission
  false

它不起作用。请帮我。提前致谢!

【问题讨论】:

  • 你能提供scopesscope的类型吗?
  • 将条件 (!result) 放在内部循环中。
  • 看到这个issue#9797

标签: javascript angularjs coffeescript


【解决方案1】:

return 将不起作用,因为它从 lambda 返回,后者被绕过到 forEach 作为第二个参数。你不应该在这里使用forEach。在 CoffeScript 中,您可以编写如下内容:

for scope in this.scopes
  for permission in scope
    return true if permission

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2013-02-16
    • 1970-01-01
    • 2011-12-01
    • 2015-06-05
    相关资源
    最近更新 更多