Understanding result returned from splice in CoffeeScript
-
28-05-2021 - |
Question
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,
Solution
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();
OTHER TIPS
splice
returns an array
.
So you need to do:
result = arr.splice(0,1)
alert result[0].do()