Contents

Roo

Array.slice()

There are two slice() methods:

First form

array.slice(index as Number) as (Object or Nothing)

Returns the element at the specified index. A negative index is permitted where -1 is the last element. This array is not modified by this operation.

Parameters

  • index. Integer Number. The index of the element to retrieve. Negative indices count backwards from the end of the array (-1 is the last element).

Returns

  • The element at the specified index. If the absolute value of index is greater than array.length then the method returns Nothing

Example

var a = ["a", "b", "c"]
a.slice(0) # => "a"
a.slice(3) # => Nothing
a.slice(-1) # => "c"

Second form

array.slice(start as Number, length as Number) as (Array or Nothing)

Returns a new array formed from the elements of this array beginning at index start, for length elements. If start is negative, we count backwards from the end of the array (-1 is the last element). This array is not modified by this operation.

Parameters

  • start. Integer Number. The index of the first element to remove. If start is negative, we count backwards from the end of the array (-1 is the last element)
  • length. Integer Number. The number of elements to remove

Returns

  • A new Array containing the elements to remove. The original array is unaltered.
  • If length < 0 returns Nothing
  • If start > array.length returns Nothing

Example

var a = ["a", "b", "c"]
a.slice(0, 0) # => Returns []
a.slice(0, 1) # => Returns ["a"]
a.slice(0, 5) # => Returns ["a", "b", "c"]
a.slice(-1, 1) # => Returns ["c"]
a.slice(-1, -1) # => Returns Nothing