using .slice method on an array

前端 未结 1 1988
南方客
南方客 2021-01-15 19:11

I\'m practicing the array section of JavaScript Koan and I\'m not fully understanding why these answers are correct. I added my assumptions below if someone could please cla

相关标签:
1条回答
  • 2021-01-15 19:42

    The second argument to Array.slice() is the upper bound of the slice.

    Think of it as array.slice(lowestIndex, highestIndex).

    When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.

    --EDIT--

    Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.

    0 讨论(0)
提交回复
热议问题