문제

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,

도움이 되었습니까?

해결책

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/

다른 팁

splice returns an array.

So you need to do:

result = arr.splice(0,1)
alert result[0].do() 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top