随机获取Uncaught TypeError:无法读取undefined的属性'substring'

时间:2014-07-28 19:14:20

标签: javascript arrays

success: function(data) {
    var timeslots = new Array('09:00am', '09:15am', '09:30am', '09:45am', '10:00am', '10:15am', '10:30am', '10:45am', '11:00am', '11:15am', '11:30am', '11:45am', '02:00pm', '02:15pm', '02:30pm', '02:45pm', '03:00pm', '03:15pm', '03:30pm', '03:45pm', '04:00pm', '04:15pm', '04:30pm');
    var booked = '';
    var bookedSlots = [];
    var t_slots;

    if (data.bookedslots.length == timeslots.length) {
        if (manageDay) {
            $('.manageSlots .timeSlot').remove();
        }
        alert('No Available Slots');
        $(where).find('select.time').empty();
        return false;
    }

    for (var t = 0; t < data.bookedslots.length; t++) {
        booked = data.bookedslots[t]['time'].substr(0, data.bookedslots[t]['time'].length - 3);
        bookedSlots.push(booked);
    }

    for (var i = 0; i < timeslots.length; i++) {
        for (var j = 0; j < bookedSlots.length; j++) {
            ///// getting the error on this line ////////if(timeslots[i].substring(0,5) === bookedSlots[j]){
            timeslots.splice(i, 1);
        }
    }
}
    for (var z = 0; z < timeslots.length; z++) {
        t_slots += '<option value="' + timeslots[z] + '">' + timeslots[z] + '</option>';
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于你拼接了时隙[i],但是在j的下一次迭代中你尝试使用它。如果它是数组中的最后一项,您将收到错误。如果你拼接,你应该在下一行中断以中止j循环的其余部分。

for (var i = 0; i < timeslots.length; i++) {
    for (var j = 0; j < bookedSlots.length; j++) {
        if(timeslots[i].substring(0,5) === bookedSlots[j]){
          timeslots.splice(i, 1);
          break;
        }
    }
}