If I have an array a
:
如果我有一个数组a:
-
a[a.length]
returnsnil
. Good. - 一个一个。长度)返回nil。好。
-
a[a.length, x]
returns[]
. Good. - 一个一个。长度,x]返回[]。好。
-
a[a.length+x, y]
returnsnil
. Inconsistent with 2. - 一个一个。长度+ x,y)返回nil。不符合2。
While this behavior is documented, it seems odd.
虽然这种行为被记录在案,但它似乎很奇怪。
Can anybody explain the reasons behind this design?
谁能解释一下这个设计的原因吗?
2 个解决方案
#1
27
Consider this
考虑一下这个
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
So a[4, 10]
is the slice between the 3
and the end of the array which is []
a[4,10]是数组3和结尾之间的切片,也就是[]
Where as a[4]
and a[5, 10]
are accessing elements that aren't in the array
当[4]和[5,10]访问不在数组中的元素时,它们在哪里
It may help to think of the slice points as being between the elements, rather than the elements themselves.
它可以帮助我们把切片点看作是元素之间的,而不是元素本身。
#2
5
Look to your friendly Lispy languages for the answer. The philosophy you're looking for began with languages whose specialty was LISt Processing. For instance, here's one way of creating lists in Haskell:
寻找你友好的Lispy语言的答案。你所寻找的哲学始于语言,它们的专长是列表处理。例如,在Haskell中有一种创建列表的方法:
1:[] => [1]
1:2:3:[] => [1,2,3]
This is called cons-ing, for 'constructing' a list. If the idea hasn't clicked yet, consider this: an array is created by adding elements to an empty list, not to 'nil'.
这被称为cons-ing,用于“构造”一个列表。如果这个想法还没有被点击,考虑一下:数组是通过向空列表中添加元素而不是“nil”来创建的。
#1
27
Consider this
考虑一下这个
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
So a[4, 10]
is the slice between the 3
and the end of the array which is []
a[4,10]是数组3和结尾之间的切片,也就是[]
Where as a[4]
and a[5, 10]
are accessing elements that aren't in the array
当[4]和[5,10]访问不在数组中的元素时,它们在哪里
It may help to think of the slice points as being between the elements, rather than the elements themselves.
它可以帮助我们把切片点看作是元素之间的,而不是元素本身。
#2
5
Look to your friendly Lispy languages for the answer. The philosophy you're looking for began with languages whose specialty was LISt Processing. For instance, here's one way of creating lists in Haskell:
寻找你友好的Lispy语言的答案。你所寻找的哲学始于语言,它们的专长是列表处理。例如,在Haskell中有一种创建列表的方法:
1:[] => [1]
1:2:3:[] => [1,2,3]
This is called cons-ing, for 'constructing' a list. If the idea hasn't clicked yet, consider this: an array is created by adding elements to an empty list, not to 'nil'.
这被称为cons-ing,用于“构造”一个列表。如果这个想法还没有被点击,考虑一下:数组是通过向空列表中添加元素而不是“nil”来创建的。