在CoffeeScript中使用indexOf

Cri*_*ian 5 javascript arrays internet-explorer-8 coffeescript

我在CoffeeScript中使用以下代码:

if elem in my_array
  do_something()
Run Code Online (Sandbox Code Playgroud)

哪个编译成这个javascript:

if (__indexOf.call(my_array, elem) < 0) {
  my_array.push(elem);
}
Run Code Online (Sandbox Code Playgroud)

我可以看到它使用了在脚本顶部定义的函数__indexOf.

我的问题是关于这个用例:我想从数组中删除一个元素,我想支持IE8.我可以做到这一点很容易indexOf,并splice在谁支持的浏览器indexOf的的array对象.但是,在IE8中,这不起作用:

if (attr_index = my_array.indexOf(elem)) > -1
  my_array.splice(attr_index, 1)
Run Code Online (Sandbox Code Playgroud)

我尝试使用__indexOfCoffeScript定义的函数,但我在编译器中得到一个保留字错误.

if (attr_index = __indexOf.call(my_array, elem) > -1
  my_array.splice(attr_index, 1)
Run Code Online (Sandbox Code Playgroud)

那么我如何使用CoffeScript或者是否有更不引人注意的方法来调用indexOf?两次定义相同的函数似乎很奇怪,因为CoffeeScript不允许我使用他们的...

Tre*_*ham 7

不,CoffeeScript阻止您直接使用其助手,因为这会打破语言和实现之间的区别.为了支持IE8,我会添加一个垫片

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

或使用像Underscore.js这样的库来进行数组操作.