gpt4 book ai didi

javascript - 随着数组变长在索引处插入元素

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

假设我有一个对象数组 var schedule

我正在遍历 forEach,通过比较当前元素的结束时间与下一个元素的开始时间来检查给定日期的日程表中是否存在间隙。如果它们不相同,那么计划中显然存在差距。

到目前为止一切正常。问题在于在正确的索引处拼接“STUFF”。目前发生的事情是......对于我拼接的每次迭代,列表长度增加一个,因此 [[magical index]] 当前没有在正确的索引处拼接。 (还不是那么神奇)。

var schedule = [{s: "9:00 AM", e: "10:00 AM"}, {s: "11:00 AM", e: "12:00 PM"}, {s: "12:00 PM", e: "2:00 PM"}, {s: "5:00 PM", e: "7:00 PM"}]

schedule.forEach((element, index) => {
if(index+1 <= schedule.length -1){
var nextElement= schedule[index+1];
if( !element.e.isSame(nextElement.s)){
//PSEDUO CODE
schedule.splice([[magical index]], 0, "STUFF");
};
};
}

所需的输出/结果看起来像这样......在原始计划数组中插入了“STUFF”var schedule = [{s: "9:00 AM", e: "10:00 AM"}, "STUFF", {s: "11:00 AM", e: "12:00 PM"} , {s: "12:00 PM", e: "2:00 PM"}, "STUFF", {s: "5:00 PM", e: "7:00 PM"}]

最佳答案

非常简单易懂的解决方案。希望对您有所帮助。

var schedule = [{s: "9:00 AM", e: "10:00 AM"}, {s: "11:00 AM", e: "12:00 PM"}, {s: "12:00 PM", e: "2:00 PM"}, {s: "5:00 PM", e: "7:00 PM"}]
var newSchedule =[]; //new array that will contains the result
const leng = schedule.length ;

schedule.forEach((element, index) => {
newSchedule.push(schedule[index]); //always add the schedule elements
if(index+1 <= leng-1 ){
var nextElement= schedule[index +1];
if( element.e !== nextElement.s){
newSchedule.push("STUFF"); //push the string "STUFF" if there is difference.
};

};
});

console.log(newSchedule);

关于javascript - 随着数组变长在索引处插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452063/

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