Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.slice - what if the end param is greater than the array length?

I can't find it - what if the end param passed to Array.prototype.slice is greater than array length?

I've tested it and it works (in Chrome), but I'm not sure if this is standard behaviour thus can be used commonly?

like image 644
LAdas Avatar asked Apr 13 '16 10:04

LAdas


People also ask

How do you slice an array at the end?

Array.prototype.slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.

Does splice change array length?

Overview. The splice() method of the Array class in JavaScript modifies the original array by changing its content. It works by removing the existing elements and adding new ones, which might change the array's length.

Can we store more elements in array than its size?

It is illegal to use a set containing more elements than the allocated size. int list[5] = {1, 2}; // array is {1, 2, 0, 0, 0} int nums[3] = {1, 2, 3, 4}; // illegal declaration.

Does slice affect array?

slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values. When you use each one is up to you.


2 Answers

If end is greater than the length of the array, it uses the length of the array. From the spec:

If relativeEnd < 0, let final be max((len + relativeEnd),0); else let final be min(relativeEnd, len).

So yes, it's standard behaviour that can be used.


Addressing this part of your question:

I can't find it

I find the quickest way is to search for "mdn array slice" - the first result is usually the relevant documentation page on the Mozilla Developer Network, in this case, this page. Each of these pages has a specifications section, which links through to the right part of the spec. It takes a little bit of getting used to how to read the specs, but it's sometimes useful to dive into them.

like image 167
James Thorpe Avatar answered Nov 01 '22 03:11

James Thorpe


Yes, it is as per the specification.

As per spec

  1. If relativeEnd < 0, let final be max((len + relativeEnd),0); else let final be min(relativeEnd, len).

Which means that final value is min of relativeEnd (end value provided as parameter) and len (length of array).

and

  1. Repeat, while k < final

So, the looping is done till the length of array if the end is not specified.

like image 20
gurvinder372 Avatar answered Nov 01 '22 04:11

gurvinder372