javascript - 获取围绕中心点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 };
},
解决方案
你可以使用一些数学来计算你得到了什么。
- 起始索引是中心点减去您想要的跨度。例如,中心
5
和跨度2
产生 的起始位置5 - 2 = 3
。 - 结束索引是中心点加上跨度。例如,中心
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));
推荐阅读
- python - 嗨,我是初学者编码器,在使用街机时,我用一个简单的程序发现了这个错误
- ios - SwiftUI - 确定当前设备和方向
- javascript - 反应导航中的自定义抽屉
- c++ - Postgres C 扩展数据类型定义
- javascript - 回调与异步回调
- java - 如何遍历 JSTL 中的对象列表
- python - 我怎样才能永远来回旋转这个对象?
- node.js - Node.js 听键盘并以交互方式阅读该行?
- search - 如何在 Prestashop 中配置搜索页面以隐藏/替换搜索结果中的不便消息抱歉
- asp.net-core - 如何在 Blazor 应用程序中重命名捆绑的静态文件(ProjectName.style.css 和 blazor.server.js)