Google News
logo
CoffeeScript - Interview Questions
What is the Array Slicing and Splicing with Ranges in CoffeeScript?
Ranges can also be used to extract slices of arrays. With two dots (3..6), the range is inclusive (3, 4, 5, 6); with three dots (3...6), the range excludes the end (3, 4, 5). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
​
start   = numbers[0..2]
​
middle  = numbers[3...-2]
​
end     = numbers[-2..]
​
copy    = numbers[..]​
var copy, end, middle, numbers, start;
​
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
​
start = numbers.slice(0, 3);
​
middle = numbers.slice(3, -2);
​
end = numbers.slice(-2);
​
copy = numbers.slice(0);​
​
The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
​
numbers[3..6] = [-3, -4, -5, -6]​
var numbers, ref,
  splice = [].splice;
​
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
​
splice.apply(numbers, [3, 4].concat(ref = [-3, -4, -5, -6])), ref;

Note that JavaScript strings are immutable, and can’t be spliced.

Advertisement