Why does array.slice behave differently for (length, n)

前端 未结 3 1670
旧时难觅i
旧时难觅i 2020-12-05 14:01

If I have an array a:

  1. a[a.length] returns nil. Good.
  2. a[a.length, x] returns []. Good.
3条回答
  •  醉酒成梦
    2020-12-05 14:46

    To begin with, this case is a special case in Ruby.

    This special case also has an explanation to it:

    There is a point of difference when you speak about indexing an array, and slicing it.

    Indexing an array means to have an unique Position which helps you access the value at a given Index.

    Slicing on the other hand means to "cut" between two points (P.S points here are index)

    Consider this:

    array = [Ruby, PHP, JS, HTML, CSS]
    

    Indexing in this case will be:

    array = [Ruby, PHP, JS, HTML, CSS]
    Index =   0.    1.  2.  3.    4. 
    

    Slicing in the same case will be:

    array = [Ruby, PHP, JS, HTML, CSS]
    Slice = 0.   1.   2.  3.    4.   5.
    

    Hence:

    array[5,n] #[] i.e. you get an empty array.
    array[6,n] #nil i.e. NIL
    

    Reference

提交回复
热议问题