I’m using the following code in CoffeeScript:
if elem in my_array
do_something()
Which compiles to this javascript:
if (__indexOf.call(my_array, elem) < 0) {
my_array.push(elem);
}
I can see it’s using the function __indexOf which is defined at the top of the script.
My question is regarding this use case: I want to remove an element from an array, and I want to support IE8. I can do that easily with indexOf and splice in browsers who support indexOf on an array object. However, in IE8 this doesn’t work:
if (attr_index = my_array.indexOf(elem)) > -1
my_array.splice(attr_index, 1)
I tried using the __indexOf function defined by CoffeScript but I get a reserved word error in the compiler.
if (attr_index = __indexOf.call(my_array, elem) > -1
my_array.splice(attr_index, 1)
So how can I use CoffeScript or is there a more unobtrusive method for calling indexOf? It seems weird to define the same function twice, just because CoffeeScript won’t let me use theirs…
No, CoffeeScript precludes you from using its helpers directly, since that would break down the distinction between the language and the implementation. To support IE8, I would add a shim like
or use a library like Underscore.js for array manipulation.