【问题标题】:Trouble with a multiple condition when statement in CoffeeScript在 CoffeeScript 中声明时出现多个条件的问题
【发布时间】:2020-04-14 07:00:08
【问题描述】:

在芬兰,与许多国家/地区一样,我们为不同的名字设置了命名日。

我正在尝试编写一个 Ubersicht 应用来显示一年中的哪一天以及那一天的名称。

我已经引入了年中的日子 (%j) 和年 (%Y),将它们拆分以便我可以操纵它们,并在 CoffeeScript 中找到了 a way 来查找闰年。

但是,由于闰年有额外的一天,2 月 29 日不是命名日(以及 1 月 1 日和 12 月 25 日),所以我想显示“今天没有名字!”在那些日子里,无论是闰年还是不是闰年。

command: "date +%j,%Y"  

update: (output) ->
  dateString = output.split(',')

  yearday = parseInt(dateString[0])
  year = dateString[1]

  leapyear = (year % 400 == 0) or (year % 4 == 0 && year % 100 != 0)


  # The Switch statement
  yearday = switch
      when (leapyear and yearday is [1, 60, 360]) then "No names today!"
      else 
        when yearday is 2 then " Aapeli "
        when yearday is 3 then " Elmer, Elmo "
        when yearday is 4 then " Ruut "

        ... and so on

我遇到的问题是我收到了ParseError: 'unexpected when'

我对构建小部件非常陌生(我知道如何在 Python 中执行此操作),但我的 switch 语句遇到了一些困难。

我也尝试过引入月日 (%d) 和月号 (%e),但我在那里遇到了类似的问题(当月 = 3 和日 = 5 时(5 月 5 日) ) 不工作)。

任何帮助将不胜感激。正如我所说,我是 CoffeeScript 新手,因此也非常感谢您的解释。

【问题讨论】:

  • ParserError 表示您正在编写它无法理解的内容,即语法错误。它还会告诉您它在哪一行遇到问题(并停止,因此在您修复第一个错误之前,您不知道是否还有其他错误。)

标签: coffeescript


【解决方案1】:

你可能想重读switch syntax

yearday = switch leapyear
  when 2 then 'Aapeli'
  when 3
    if additional_conditionals then A else B
  when 4 then 'Ruut'
  else 'No names today!'
  # else is default, you can't nest additional when statements here

但是,更简单的解决方案是使用数组。 (这并不完全是关于 Coffeescript,而是适用于对编程的一般思考。)

dayNames = ['', '', 'Aapeli', 'Elmer, Elmo', 'Ruut']
dayName = (day) => switch day
  when 0 then 'fails, no 0th day' # optional
  when 1, 60, 360 then 'No names today!'
  else "Name of day #{day} is #{dayNames[day]}."

# Additionally, don't prewrite the spaces.
# Use string manipulation like above instead
# (note the difference between single and double quotes)

console.log dayName 4
# 'Name of day 4 is Ruut.'
console.log dayName 60
# 'No names today!'

(顺便说一句,请删除有关芬兰日的额外信息,这无关紧要..)

干杯:)

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2014-06-20
    • 2018-02-25
    相关资源
    最近更新 更多