简体   繁体   English

更好的做事方式:总是从阵列中取出6件物品

[英]Better way of doing: Always get a range of 6 Items out of an array

i need a little bit algorithm help. 我需要一点算法帮助。

I want to extract a range of 6 items out of an array. 我想从数组中提取6个项目的范围。 Starting point is a given index, if possible i want to get the items evenly split up before and after the given index. 起点是给定索引,如果可能的话,我想让项目在给定索引之前和之后平均分配。

I already did it, but i search for a more elegant way than just shifting the range. 我已经做到了,但是我寻找的不仅仅是改变范围。 How can i improve my code? 如何改善我的代码?

 const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]; const area = 7; const currentIndex = 5; const arrayLength = array.length; let rangeBegin = currentIndex - Math.floor((area - 1) / 2); let rangeEnd = currentIndex + Math.ceil((area - 1) / 2); if (rangeBegin < 0) { const offset = -rangeBegin; rangeBegin += offset; rangeEnd += offset; } if (rangeEnd >= arrayLength) { const offset = rangeEnd - arrayLength; rangeBegin -= offset; rangeEnd -= offset; } slicedArray = array.slice(rangeBegin, rangeEnd); console.log(slicedArray) 

https://playcode.io/377252?tabs=script.js,preview,console https://playcode.io/377252?tabs=script.js,preview,console

You could move the index by subtracting the half size and take a max value for negative indices and a min value for indices which are greater than the array length minus the size of the wanted sub array. 您可以通过减去一半大小来移动索引,并为负索引取最大值,对于大于数组长度减去所需子数组大小的索引取最小值。

  value array index adj max min ----- ------------------------------ ----- --- --- --- v 2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1 -1 0 0 [ ] v 5 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 4 2 2 2 [ ] vv 10 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 9 7 7 5 [ ] 

 function getSub(array, index, size) { if (size >= array.length) return array; var pivot = Math.floor(index - (size - 1) / 2), max = Math.max(pivot, 0), min = Math.min(max, array.length - size); return array.slice(min, min + size); } console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, 5)); console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4, 5)); console.log(...getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9, 5)); console.log(...getSub([1, 2, 3, 4], 1, 5)); console.log(...getSub([1, 2, 3, 4], 4, 5)); console.log(...getSub([1, 2, 3, 4], 9, 5)); 

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
const area = 7;
const currentIndex = 5;
const arrayLength = array.length;


let rangeBegin = currentIndex - Math.floor((area - 1 ) /2);
if(rangeBegin < 0) {
  rangeBegin = 0;
}
let rangeEnd = rangeBegin + area - 1;
if(rangeEnd >= arrayLength) {
  rangeEnd = arrayLength;
  rangeBegin = arrayLength - area;
}

slicedArray = array.slice(rangeBegin, rangeEnd);

!!! This code not checks if length of array lower than area we need. 此代码不检查数组的长度是否小于我们所需的面积。

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

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