Is there an equivalent for ruby's array[n..m] in Javascript ?
For example:
>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']
Thanks
Is there an equivalent for ruby's array[n..m] in Javascript ?
For example:
>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']
Thanks
The second argument in
slice
is optional, too:You can also pass a negative number, which selects from the end of the array:
Here's the W3 Schools reference link.
Use the
array.slice(begin [, end])
function.The last index is non-inclusive; to mimic ruby's behavior you have to increment the
end
value. So I guessslice
behaves more likea[m...n]
in ruby.Ruby and Javascript both have a slice method, but watch out that the second argument to slice in Ruby is the length, but in JavaScript it is the index of the last element:
a.slice(0, 3)
Would be the equivalent of your function in your example.https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice