在 mu 中添加一点点是太短的答案,您可以将其第二个代码片段转换为switch
表达式:
Handlebars.registerHelper 'status', (blog) ->
status = parseInt(blog.status, 10)
switch
when status <= 0 then 'Something...'
when status <= 20 then 'Active'
when status <= 40 then 'Moderately Active'
when status <= 60 then 'Very Active'
when status <= 100 then 'Hyper Active'
else 'Something else'
这基本上相当于switch (true)
在 JavaScript 中执行 a (尽管 CS 编译器将生成一个switch (false)
带有否定条件的语句以确保表达式的布尔结果......我认为)。
switch
超出范围不起作用的原因是 CS 中的范围文字表示普通的旧 JS 数组(尽管编译器在执行类似的操作时会做一些优化技巧for i in [1..something]
),所以当它们在 a 中被发现时,它们会switch
被视为正常数组值:
// Generated JS for question's CS code:
switch (parseInt(blog.status)) {
case [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]:
status = "active";
break;
case [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]:
status = "Moderately Active";
break;
case [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]:
status = "Very Active";
break;
case (function() {
_results = [];
for (_i = 60; _i <= 100; _i++){ _results.push(_i); }
return _results;
}).apply(this):
status = "Hyper Active";
}
语句中的值switch
基本上与 using 的每个case
值进行比较===
,它仅适用于基元,不适用于数组(即使它适用于数组,它也会测试数组相等性,而不是switch
ed 值是否包含在case
ed 数组中) .