Pregunta

I am using CoffeeScript along with the JS splice function. My understanding of the JS splice function is that it should return the objects that were spliced out and modify the original array. This seems to work ok with simple arrays but when I start adding objects to the array things break down. Below is a simplified case with comments:

And a link code

#Class that will go in array
class Thing
  do: ->
    alert "Hi"

a = new Thing
b = new Thing

arr = []

arr.push(a)
arr.push(b)

arr[0].do()  # this works

result = arr.splice(0,1)
alert result.do()  # this does not work

Does splice do something that makes this not work? If anyone has an idea about the reason this is happening and/or a fix, I would be very appreciative,

¿Fue útil?

Solución

Array.splice() returns an array of the element(s) removed; as it has the potential to remove multiple via the second parameter:

Because of this, you should be using alert result[0].do();

Working example: http://jsfiddle.net/Cjtaa/

Otros consejos

splice returns an array.

So you need to do:

result = arr.splice(0,1)
alert result[0].do() 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top