繁体   English   中英

根据位置从数组中获取N个元素

[英]Get the N elements from array based on the position

我想要一个返回子数组的函数,该子数组需要一个位置和编号。 我想要的元素。 我认为可能有一些算法可以找到枢轴点或其他东西,从中我可以得到子数组,但是我完全忘记了。

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 ,该loop将包含多个if-else条件来完成它。 但是我觉得可能有一些简单的方法可以做到这一点。

我没有包含不完整的代码片段,因为我强烈认为必须有某种算法才能执行此操作。

您想要的是: Array.prototype.slice(...)

它整齐地记录在这里: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

var n = 6;
var start = Math.max(0, Math.min(Math.floor(position-n/2), a.length-n));
return a.slice(start, start+n);

简单方法:

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function getSubArray(idx, _length, _array) {
  return _array.slice(idx, idx + _length);
}

var subArray = getSubArray(3, 6, a);

您可以为该位置使用偏移量,并首先获取起始值以进行切片。

 var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n = 6, i, start; for (i = 1; i < 12; i++) { start = Math.max(Math.min(i - n / 2, a.length - n), 0); console.log(i, ': ', a.slice(start, start + n).join()); } 

您唯一需要检查的是是否不存在的pos。 喜欢 :

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var n = 6; // Number of result you want
var x = 8; // Pos you want

// If you gonna exceed your length, we got only the n last element
if((x+(n/2)) > a.length) { 
    console.log(a.slice(a.length-n)); 
// Otherwise, if under 0, we got the n first
} else 
    if((x-(n/2)) < 0) { console.log(a.slice(0,n) ); 
// Default case
    } else { 
console.log(a.slice((x-(n/2)),(x+(n/2))));
}

这不是最聪明的方法,但是他可以给您一些提示。 我使用了其他提到的切片来避免很多if,但是您应该进行GENERIC测试。

像这样的东西:

a = [1,2,3,4,5,6,7,8,9,10];
n = 6;
function split(position) {
    var start = Math.min(Math.max(position - Math.floor(n/2), 0), a.length - n);
    var stop = Math.min(start+n, a.length);
    return a.slice(start, stop);
}

完全不需要Math对象。 您可以简单地执行以下操作;

 function getArr(a,n,d){ n = n - 4 < 0 ? 0 : a.length - d > n - 4 ? n - 3 : a.length - d; return a.slice(n,n + d); } var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], diff = 6; for (var i = 0; i < 10; i ++) console.log(JSON.stringify(getArr(arr,i,diff))); 

无需if-else,您可以使用arr [position]到arr [8]。 你有吗

function getArr(arr,position,requiredNumbers){
return arr.slice(position, position+requiredNumbers);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM