【问题标题】:Unlabeled break must be in loop in Coffeescript未标记的中断必须在 Coffeescript 中循环
【发布时间】:2015-04-20 20:44:09
【问题描述】:
sheet = [1,2,3,4,5,6,7,8,9,10]
myArray = []
batchSize = 0
sheetSize = sheet.length

eat = (item) ->
  loop
    batchSize++
    sheetSize--
    myArray.push item
        break unless batchSize < 2 or sheetSize > 0
  batchSize = 0
  document.write "myArray", myArray  
  myArray = []

eat item for item in sheet

http://codepen.io/nottinhill/pen/dobXvE

我想打印上面的代码:

1,2 
3,4 
5,6 
7,8 
9,10 

但是它不起作用,unlabeled break must be in loop 失败

【问题讨论】:

  • 我收到unexpected indentation 警告。此外,该算法可能不会那样工作。你想“吃掉”数组的内容吗?那么... 可能会派上用场,如果您不关心变量的大小。如果你想要更多的变量,看看Array.slice
  • 完全忘记了递归。这就是在传统媒体公司工作对你的影响。
  • @PatrickJ.S.您的第二个算法非常优雅,使用了许多我不知道的 CoffeeScript 语法。将其作为下面的答案进行解释,我会给你答案,或者如果你能解释一下“start if start”是如何工作的。

标签: javascript coffeescript


【解决方案1】:

根据要求,我将发布该问题的其他解决方案。我收到原始问题中脚本的另一条错误消息(错误的缩进),所以我无法回答。

递归:

  eatVar = (batch_Size) ->
  eatSome = (sheet, start = 0) ->
    sheet.slice start,batch_Size
    end = start+batch_Size
    document.write sheet.slice start, end
    document.write "<br>"
    eatSome sheet, end if end < sheet.length

至于最后一行:相当于

if end < sheet.length
  eatSome sheet, end

但你不必递归:

eatVar2 = (batch) -> (sheet, start) ->
  position = 0
  for elem in sheet
    document.write elem
    document.write if ++position % batch then ', ' else '<br>'

(eatVar2 2) sheet

这是Codepen。我真的希望这是一种任务,因为我非常不鼓励你使用document.write。有更好的方法来生成 HTML,比如document.body.appendChild document.createTextNode "foobarbaz"

【讨论】:

  • 谢谢帕特里克!我将document.write 仅用于 CodePen,上次我在生产中使用document.write 是 1992 年。该函数是我针对节点 MongoDB 本地驱动程序 100 批限制问题的 Mongoose 解决方法的抽象形式,我可能会在此发布我的博客。
  • 嘿,我更新了笔,现在有一个带有变量功能的版本,你可以用它来替换文档写入。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多