user578895
user578895

Reputation:

Is Array.slice with negative numbers safe?

I remember reading years ago that passing negative numbers as the 2nd argument to some of the functions with this syntax (slice, substr, etc) was only supported in some browsers, but I can't find the reference.

Just wondering if anyone knows if ary.slice(0, -1) specifically is safe across all browsers.

Upvotes: 12

Views: 14388

Answers (2)

Naphtali Duniya
Naphtali Duniya

Reputation: 134

Yes, it is safe for browsers, but buggy in Internet Explorer 4 which is later fixed in later versions of IE. Also, be mindful of how the indexing goes, positive value indexes from 0 to length [start to end] but using a negative value, starts from behind or .length obviously, but indexes from -1 and not -0 as expected. And for the end argument indexing goes the same way, but instead of not returning the end value and replacing with the next value, it rather replaces its end value with the previous value. Just a little note.

let a = [1,2,3,4,5];
a.slice(0,3);    // Returns [1,2,3]
a.slice(3);      // Returns [4,5]
a.slice(1,-1);   // Returns [2,3,4]
a.slice(-3,-2);  // Returns [3]; buggy in IE 4: returns [1,2,3]

Upvotes: 3

tonythewest
tonythewest

Reputation: 516

Using a negative number for either the start or end value (or both) is safe and will select from the end of the array. It is supported across IE, FF, Chrome, Safari, and Opera.

Upvotes: 14

Related Questions