【发布时间】:2017-03-24 12:33:50
【问题描述】:
我想要一个函数,它返回一个位置和编号的子数组。我想要的元素。我认为可能有一些算法可以找到枢轴点或其他东西&从中我可以得到子数组,但我完全忘记了。
Example: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want 6 elements
if position = 0, then I want [1, 2, 3, 4, 5, 6]
if position = 1, then [1, 2, 3, 4, 5, 6]
if position = 2, then [1, 2, 3, 4, 5, 6]
if position = 3, then [1, 2, 3, 4, 5, 6]
if position = 4, then [2, 3, 4, 5, 6, 7]
if position = 5, then [3, 4, 5, 6, 7, 8]
if position = 6, then [4, 5, 6, 7, 8, 9]
if position = 7, then [5, 6, 7, 8, 9, 10]
if position = 8, then [5, 6, 7, 8, 9, 10]
if position = 9, then [5, 6, 7, 8, 9, 10]
simply get the middle of N elements based on the position I pass.
我可以编写自己的loop,其中将包含多个if-else 条件来完成它。但我觉得可能有一些简单的方法可以做到这一点。
我没有包含我不完整的代码 sn-p,因为我强烈认为必须有一些算法来做到这一点。
【问题讨论】:
-
仓位是怎么用的?为什么指定位置为 4 时跳过第一个元素?
-
这就像,如果我的位置是数组的中心位置,让我得到具有 N 个元素的中间数组。有意义吗
-
好的,我错过了,我得到了一个起始索引和最小长度。我会相应地更新我的 sn-p。 :)
标签: javascript arrays algorithm