【问题标题】:basic coffeescript find if in array基本的咖啡脚本查找是否在数组中
【发布时间】:2013-09-13 02:35:26
【问题描述】:

在咖啡脚本中,我试图确定数组中是否包含某些内容。但似乎无法弄清楚正确的语法。有没有办法做到这一点而不必迭代它们?

谢谢,

  if $(this).val() is in ["needs_cover","comatose"]
    $("#head_count").hide()
  else
    $("#head_count").show()

【问题讨论】:

  • $(this).val() in ["needs_cover", "comatose"] 应该可以工作。
  • 我知道我很接近谢谢!

标签: javascript arrays if-statement coffeescript


【解决方案1】:

只需删除is

if $(this).val() in ["needs_cover","comatose"]
    $("#head_count").hide()
  else
    $("#head_count").show()

这将转换为以下 JavaScript:

var _ref;

if ((_ref = $(this).val()) === "needs_cover" || _ref === "comatose") {
  $("#head_count").hide();
} else {
  $("#head_count").show();
}

【讨论】:

    【解决方案2】:

    如果这是一个常见的用例,您可以编写一个函数,这也可以让您编写一个更紧凑的例程,如下所示:

    hideShowFn = (valSelector, hideShowElSelector, compareArr) ->
        if $(valSelector).val() in compareArr then return $(hideShowElSelector).hide()
        $(hideShowElSelector).show()
    

    我更喜欢执行上述操作,因为它会使代码稍微扁平化。这是我的偏好。

    你可以这样调用函数:

    hideShowFn this, '#head_count', ['needs_cover', 'comatose']
    

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      相关资源
      最近更新 更多