假设我有以下数组:
[
{start: "0", end: "3"},
{start: "4", end: "6"},
{start: "2", end: "8"}
]
如您所见,第三个对象与前两个间隔重叠。为此,我创建了以下功能:
checkOverlap = function(o1, o2){
return ((o1.end - o2.start) >= 0 && (o2.end - o1.start) >= 0) ? true : false;
}
我写了这段代码:
for (var i = 0; i < array.length; i++)
{
for(var x = 0; x < array.length; x++){
if(this.checkOverlap(array[i], array[x])){
throw new Error("overlap detected");
}
}
}
但是在没有重叠的情况下也会产生错误
如何遍历数组并比较每个索引以查看至少一个对象间隔是否与另一个对象间隔重叠?
答案 0 :(得分:1)
您的代码存在的问题是您也在检查每个项目的自身。
如果您排除它应该工作。 (添加o1 !== o2
支票)
const array = [
{start: "0", end: "3"},
{start: "4", end: "6"},
{start: "2", end: "8"}
]
checkOverlap = function(o1, o2){
return o1 !== o2 && ((o1.end - o2.start) >= 0 && (o2.end - o1.start) >= 0) ? true : false;
}
for (var i = 0; i < array.length; i++)
{
for(var x = 0; x < array.length; x++){
if(this.checkOverlap(array[i], array[x])){
throw new Error("overlap detected");
}
}
}
这是另一种仅用于语法糖的方法
const ranges = [
{start: "0", end: "3"},
{start: "4", end: "6"},
{start: "5", end: "8"}
];
const overlapCheck = (A,index,arr) => arr.some(B=>A!==B && (A.start < B.end && A.end > B.start))
const isOverlap = ranges.some(overlapCheck)
console.log(isOverlap)