簡體   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