Using indexOf in CoffeeScript

I use the following code in CoffeeScript:

if elem in my_array
  do_something()

What compiles with this javascript:

if (__indexOf.call(my_array, elem) < 0) {
  my_array.push(elem);
}

I see this using the __indexOf function, which is defined at the top of the script.

My question is about this use case: I want to remove an element from an array, and I want to support IE8. I can easily do this with indexOfand splicein browsers that support indexOfthe object array. However, in IE8 this does not work:

if (attr_index = my_array.indexOf(elem)) > -1
  my_array.splice(attr_index, 1)

I tried using a function __indexOfdefined by CoffeScript, but I received a reserved word error in the compiler.

if (attr_index = __indexOf.call(my_array, elem) > -1
  my_array.splice(attr_index, 1)

, CoffeScript indexOf? , , CoffeeScript ...

+5
2

, CoffeeScript , . IE8, ,

Array::indexOf or= (item) ->
  for x, i in this
    return i if x is item
  return -1

, Underscore.js .

+7

CoffeeScript :

var __indexOf = [].indexOf || function(item) {
  for (var i = 0, l = this.length; i < l; i++) {
    if (i in this && this[i] === item) return i;
  }
  return -1;
};

, :

indexOf = __indexOf

: RESERVED WORD "__INDEXOF"

, :

indexOf = `__indexOf`

indexOf.call([1,2,3,4], 3) //2

@Trevor Burnham:

Array::indexOf or= `__indexOf`

, CoffeeScript , in ( ). , :)

+2

All Articles