我在 Rails 3.2 jquery 移动应用程序中使用 Handlebar。
我正在尝试在 Coffeescript 方法中编写一个 switch case 语句,例如
Handlebars.registerHelper 'status', (blog) ->
switch(parseInt(blog.status))
when [0..20]
status = "active"
when [20..40]
status = "Moderately Active"
when [40..60]
status = "Very Active"
when [60..100]
status = "Hyper Active"
return status
我没有得到任何结果。如何在 when 中使用范围。请建议
最佳答案
您的 switch
不能用作 Cygal注释中的注释(即见 issue 1383 )。一个 switch
只是一个荣耀if(a == b)
构造,并且您需要能够说出以下内容:
a = [1,2,3]
switch a
...
并在您
switch
时让它工作在一个数组上。 CoffeeScript 设计者认为添加一个(脆弱的)特殊情况来处理数组(这是所有 [a..b]
)是不值得的。你可以用
if
:Handlebars.registerHelper 'status', (blog) ->
status = parseInt(blog.status, 10)
if 0 <= status <= 20
'Active'
else if 20 < status <= 40
'Moderately Active'
else if 40 < status <= 60
'Very Active'
else if 60 < status <= 100
'Hyper Active'
else
# You need to figure out what to say here
或短路
return
像这样:Handlebars.registerHelper 'status', (blog) ->
status = parseInt(blog.status, 10)
return 'Something...' if status <= 0
return 'Active' if status <= 20
return 'Moderately Active' if status <= 40
return 'Very Active' if status <= 60
return 'Hyper Active' if status <= 100
return 'Something else' # This return isn't necessary but I like the symmetry
请注意,您需要为以下三种特殊情况添加字符串:
status < 0
. status > 100
. status
是 NaN
.这种情况通常属于最后的“它不小于或等于 100”分支,因为 NaN => n
和 NaN <= n
都是假的 n
. 是的,您绝对确定状态将始终处于假定范围内。另一方面,不可能的事情一直在软件中发生(因此是 comp.risks 邮件列表)并且没有充分的理由留下如此容易填补的漏洞。
还要注意在
parseInt
中添加了 radix 参数。打电话,你不希望前导零把事情弄得一团糟。是的,基数参数是可选的,但它真的不应该是,你的手指应该自动添加 , 10
到每个 parseInt
调用你。
关于coffeescript - Coffeescript中switch case语句内的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11202492/