首页 > 解决方案 > 在 CoffeeScript 中声明时出现多个条件的问题

问题描述

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

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

我引入了年中的日子 ( %j) 和年 ( %Y),将它们分开以便我可以操纵它们,并找到了一种在 CoffeeScript 中找到闰年的方法。

但是,因为闰年​​有额外的一天,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

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

标签: coffeescript

解决方案


您可能想重新阅读switch语法

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!'

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

干杯:)


推荐阅读