Javascript for循环检查间隔重叠

时间:2016-04-26 12:52:36

标签: javascript

我有以下javascript功能(感谢Nina Scholz)。

function overlapping(a, b) {
function getMinutes(s) {
    var p = s.split(':').map(Number);
    return p[0] * 60 + p[1];
}
return getMinutes(a.end) > getMinutes(b.start) && getMinutes(b.end) >   getMinutes(a.start);
}

我现在的问题是我有例如4intervals:

var myArray = [{ start: '01:00', end: '04:00' }
{ start: '05:00', end: '08:00' }
{ start: '07:00', end: '11:00' }
{ start: '09:30', end: '18:00' }]

现在我将检查是否有任何间隔与另一个间隔重叠。

var overlap = false;
for(var n = 0; n < myArray.length; n++) {
    for(var i = 0; i < n; i++) {
       var result = overlapping(myArray[n], myArray[i]);
       if(result == true) {
         overlap = result;
         break;
       }
    }
}

我现在的问题是,如果这是正确的,或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

提案会检查阵列中的所有元素与其他元素。如果找到重叠,则迭代停止并返回true。否则false

function overlapping(a, b) {
    function getMinutes(s) {
        var p = s.split(':').map(Number);
        return p[0] * 60 + p[1];
    }
    return getMinutes(a.end) > getMinutes(b.start) && getMinutes(b.end) > getMinutes(a.start);
}

function isOverlapping(array) {
    var i, j;
    for (i = 0; i < array.length - 1; i++) {
        for (j = i + 1; j < array.length; j++) {
            document.write('test ' + i + ' vs ' + j + '<br>');
            if (overlapping(array[i], array[j])) {
                return true;
            }
        }
    }
    return false;
}

var myArray = [{ start: '01:00', end: '04:00' }, { start: '05:00', end: '08:00' }, { start: '07:00', end: '11:00' }, { start: '09:30', end: '18:00' }];

document.write(isOverlapping(myArray));