Array splicing with coffeescript, what is _ref for?
-
13-12-2019 - |
Question
In the CoffeeScript docs for array splicing, what is the purpose of the trailing , _ref
?
CoffeeScript:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
Compiles to:
var numbers, _ref;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;
La solution
That's because CoffeeScript's slicing operation wants to return the slice it has just assigned, but splice() returns the removed elements instead.
So, in order to achieve this, it compiles the construct into a code fragment that first assigns the slice to a local _ref
variable, then uses the comma operator to return that variable after calling splice()
.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow