首页 > 解决方案 > 获取围绕中心点js的位置窗口

问题描述

我试图弄清楚如何根据 JavaScript 中的中心点获取位置窗口。

假设我有以下数组: [0,1,2,3,4,5,6,7,8,9]

如果我想将位置 5 作为中心点,我还想获得位置 3、4、6 和 7,这将产生 [3,4,5,6,7]。

但是,我也试图让它在数组的左边界或右边界范围内时,它将窗口推向相反的方向。例如,如果我想要位置 1,我希望数组返回为 [0,1,2,3,4]。或者,如果我想要位置 0,我希望数组为 [0,1,2,3,4]。这同样适用于数组的末尾,例如,我想获得位置 8,所以我会返回 [5,6,7,8,9]。

我正在努力将它融入 JavaScript,我觉得我把事情复杂化了。我当前的代码如下,但是我根本没有附加到这个代码,所以完全改变它很好:

positions() {
    let left = 0;
    let right = 5;
    let middle = this.steps.length / 2;
    // Closer to left.
    if (this.index < middle) {
        if (this.steps[this.index - 2]) {
            left = this.index - 2;
            right = this.index + 2;
        }
        else if (this.steps[this.index - 1]) {
            left = this.index - 1;
            right = this.index + 3;
        }
    }
    // Closer to right.
    else if (this.index > middle) {
        if (this.steps[this.index + 3]) {
            left = this.index - 2;
            right = this.index + 3;
        }
        else if (this.steps[this.index + 2]) {
            left = this.index - 3;
            right = this.index + 2;
        }
        else if (this.steps[this.index + 1]) {
            left = this.index - 4;
            right = this.index + 1;
        }
    }
    else {
        left = this.index - 2;
        right = this.index + 3;
    }
    return { left, right };
},

标签: javascriptarraysmathecmascript-6

解决方案


你可以使用一些数学来计算你得到了什么。

  1. 起始索引是中心点减去您想要的跨度。例如,中心5和跨度2产生 的起始位置5 - 2 = 3
  2. 结束索引是中心点加上跨度。例如,中心5和跨度2产生 的结束位置5 + 2 = 7
[0,1,2,3,4,5,6,7,8,9]
       ^   ^   ^
       |   |   |
start -+   |   |
centre +---+   |
end ---+-------+
       |       |
      [3,4,5,6,7]

要处理“溢出”,您可以限制开始/结束值。

  • start 不能低于数组的开头(即0)。
  • 而 end 最多可以是数组的最后一个位置(即arr.length - 1)。

如果开始或结束位置形成的跨度小于预期的跨度,则可以将剩余部分转移到相反的索引:

的中心1和跨度为2

       [0,1,2,3,4,5,6,7,8,9]
        ^ ^     ^
        | |     |
start --+ |     |
centre ---+     |
padded end -----+

的中心8和跨度为2

       [0,1,2,3,4,5,6,7,8,9]
                  ^     ^ ^
                  |     | |
padded start -----+     | |
centre -----------------+ |
end ----------------------+

最后,唯一需要处理的情况是如果数组不够大会发生什么。这取决于您,只返回整个数组是明智的,但您也可以选择抛出错误或空数组。如果您确定它永远不会发生,您也可以不处理它。

这是实现的外观

function getRange(arr, pos, span) {
  if ((span*2 + 1) > arr.length) {
    throw Error("not enough items in array"); //or just return arr; or return []; etc.
  }
  
  let start = Math.max((pos - span), 0);
  let end = Math.min((pos + span), arr.length - 1);
  
  const leftoverStart  = span - (pos - start);
  const leftoverEnd    = span - (end - pos);
  
  if (leftoverStart) {
    end += leftoverStart;
  } else if (leftoverEnd) {
    start -= leftoverEnd;
  }
  
  return arr.slice(start, end+1);
}

const arr = [0,1,2,3,4,5,6,7,8,9];

console.log(getRange(arr, 5, 2));
console.log(getRange(arr, 1, 2));
console.log(getRange(arr, 8, 2));


推荐阅读