ere
ere

Reputation: 1779

basic coffeescript find if in array

In coffee script I'm trying to figure out if something is included in an array or not. But can't seem to figure out the correct syntax. Is there not a way to do this without have to iterate over them?

Thanks,

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

Upvotes: 1

Views: 933

Answers (2)

TheRocketSurgeon
TheRocketSurgeon

Reputation: 146

If this is a common use case, you could write a function, which would also allow you to write a routine that is a bit more compact as well, like so:

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

I prefer doing the above as it flattens the code a little bit. This is my preference.

You would call the function like so:

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

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173642

Just drop the is:

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

That would translate to the following JavaScript:

var _ref;

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

Upvotes: 6

Related Questions