为什么 array.slice 对于 (length, n) 的行为不同 [英] Why does array.slice behave differently for (length, n)

查看:20
本文介绍了为什么 array.slice 对于 (length, n) 的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数组a:

  1. a[a.length] 返回 nil.很好.
  2. a[a.length, x] 返回 [].很好.
  3. a[a.length+x, y] 返回 nil.与 2 不一致.
  1. a[a.length] returns nil. Good.
  2. a[a.length, x] returns []. Good.
  3. a[a.length+x, y] returns nil. Inconsistent with 2.

虽然这种行为被记录,但似乎很奇怪.

While this behavior is documented, it seems odd.

谁能解释一下这种设计背后的原因?

Can anybody explain the reasons behind this design?

推荐答案

考虑一下

a = [0, 1, 2, 3] #=> [0, 1, 2, 3]
a[0, 10]         #=> [0, 1, 2, 3]
a[1, 10]         #=>    [1, 2, 3]
a[2, 10]         #=>       [2, 3]
a[3, 10]         #=>          [3]
a[4, 10]         #=>           []
a[5, 10]         #=>          nil

所以 a[4, 10]3 和数组末尾之间的切片,即 []

So a[4, 10] is the slice between the 3 and the end of the array which is []

其中 a[4]a[5, 10] 正在访问不在数组中的元素

Where as a[4] and a[5, 10] are accessing elements that aren't in the array

将切片点视为位于元素之间而不是元素本身可能会有所帮助.

It may help to think of the slice points as being between the elements, rather than the elements themselves.

[ <0> 0 <1> 1 <2> 2 <3> 3 <4> ]

其中 是元素和数组开始/结束之间的点.a[4, 10] 然后变成 10 个元素的选择,从第 4 点开始.而 a[5, 10] 从第 5 点开始,它不是清单.

Where <n> are the points between elements and the start/end of the array. a[4, 10] then becomes a selection of 10 elements, starting from point 4. Whereas a[5, 10] starts from point 5, which is not part of the list.

这篇关于为什么 array.slice 对于 (length, n) 的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆