最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is Array.slice with negative numbers safe? - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question asked Jan 20, 2017 at 22:32 user578895user578895 5
  • 3 According to MDN, passing a negative index to Array#slice was supported since ES3, which all browsers support. – Felix Kling Commented Jan 20, 2017 at 22:34
  • @Felix, I was just on MDN myself looking for an authoritative answer. – Octopus Commented Jan 20, 2017 at 22:35
  • @FelixKling - Thanks, if you answer I'll accept :) – user578895 Commented Jan 20, 2017 at 22:35
  • 1 I think the problem was with substr and substring, not with slice. – Oriol Commented Jan 20, 2017 at 22:35
  • @Oriol - good to know! – user578895 Commented Jan 20, 2017 at 22:36
Add a comment  | 

2 Answers 2

Reset to default 13

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.

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]
发布评论

评论列表(0)

  1. 暂无评论