gpt4 book ai didi

javascript - 选择 Array 中给定索引任一侧最近的 2 个元素

转载 作者:行者123 更新时间:2023-11-30 08:29:37 24 4
gpt4 key购买 nike

我需要从数组中的给定索引的任一侧返回一个包含 2 个项目的新数组。

考虑这个时间数组:

const times = ['17:30', '17:45', '18:00', '18:15', '18:30', '18:45', '19:00', '19:15', '19:30', '19:45', '20:00'];

我需要做的是选择索引为 5 的数组项并返回该项,以及两侧的 2 个。这很简单,但是,如果给我的索引是 1 或 0,甚至是数组长度的末尾,我的代码将无法运行。 我总是想退回 5 件商品

考虑我目前拥有的以下(非常粗糙的)代码:

const times = ['17:30', '17:45', '18:00', '18:15', '18:30', '18:45', '19:00', '19:15', '19:30', '19:45', '20:00'],
givenTime = '19:00';

console.clear();
console.log(getNearestTimes(times, givenTime));

function getNearestTimes(times, givenTime) {

const nearestTimes = times.filter((element, index, array) => {
const selected = array.indexOf(givenTime);
const diffBefore = array.slice(0, selected).length,
diffAfter = (diffBefore >= 2) ? 2 : (diffBefore + 4);

if ((index >= (selected - diffAfter) && index < selected) || (index >= selected && index <= (selected + diffAfter)) ) {
return element;
}

});

return nearestTimes;

}

'19:00' 看起来不错,返回:

["18:30", "18:45", "19:00", "19:15", "19:30"]

'17:30' 看起来不错,返回:

["17:30", "17:45", "18:00", "18:15", "18:30"]

但是,'19:45' 看起来不太好,返回:

["19:15", "19:30", "19:45", "20:00"]

...理想情况下,“19:45”会返回:

["19:00", "19:15", "19:30", "19:45", "20:00"]

如果在给定时间之后没有足够的项目,我想在那之前返回更多,总是返回 5 个数组项目。

我希望这是有道理的?它几乎就像一个数组 block ,但只是来自数组索引,而不是我想返回的数组数量。

谢谢!

最佳答案

您可以通过一些检查来更正开始和结束索引。

function getNearestTimes(times, givenTime) {
var i = times.indexOf(givenTime),
start = i - 2,
end = i + 3;

if (start < 0) {
start = 0;
end = 5;
}
if (end > times.length) {
end = times.length;
start = end - 5;
}
return times.slice(start, end);
}

const times = ['17:30', '17:45', '18:00', '18:15', '18:30', '18:45', '19:00', '19:15', '19:30', '19:45', '20:00'];

console.log(getNearestTimes(times, '19:00'));
console.log(getNearestTimes(times, '17:45'));
console.log(getNearestTimes(times, '20:00'));

上面的一些较短的代码,在开始时有压力。

function getNearestTimes(times, givenTime) {
var i = times.indexOf(givenTime) - 2;
i = Math.min(Math.max(0, i), times.length - 5)
return times.slice(i, i + 5);
}

const times = ['17:30', '17:45', '18:00', '18:15', '18:30', '18:45', '19:00', '19:15', '19:30', '19:45', '20:00'];

console.log(getNearestTimes(times, '19:00'));
console.log(getNearestTimes(times, '17:45'));
console.log(getNearestTimes(times, '20:00'));

关于javascript - 选择 Array 中给定索引任一侧最近的 2 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39956967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com