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.
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.
2 Answers
Reset to default 13Using 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.
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]
Array#slice
was supported since ES3, which all browsers support. – Felix Kling Commented Jan 20, 2017 at 22:34substr
andsubstring
, not withslice
. – Oriol Commented Jan 20, 2017 at 22:35