为什么列表中创建了5个元素?需要创建提示功能的JavaScript

问题描述

主要焦点在JS内,“添加约会”功能正在循环,并且“年”值最终以5个元素的列表结尾,即使仅进行了一次约会也是如此。我认为从添加约会功能创建了两个额外的功能,从并发约会功能创建了另外两个功能。这是一个小组项目,我没有做这个组件,这就是为什么我一直在努力理解和解决这个问题。

我正在尝试将yy变量推入年份列表,然后创建一个提示功能以列出每年有多少约会。

任何建议都将受到高度赞赏!如果我还不够详细,请告诉我! :)

预先感谢

    <html>

<head>
    <script>
        const MIN_YEAR = 2019;
        var years = [];
        var list = [];
        let appointment = {
            date: "",startTime: "",endTime: "",subject: "",venue: "",rowData: function () {
                return "<tr><td>" + this.date + "</td><td>" + this.startTime + "</td><td>" + this.endTime + "</td><td>" + this.subject + "</td><td>" + this.venue + "</td><td>" + this.priority + "</td></tr>";
            }
        }

        function addAppointment() {
            let newAppointment = Object.create(appointment);

            var startIndex = document.getElementById('startTime').selectedindex;
            var priority;

            newAppointment.startTime = document.getElementById('startTime').options[startIndex].value;
            newAppointment.subject = document.getElementById('subject').value;
            newAppointment.venue = document.getElementById('venue').value;


            if (validDate() != false) { newAppointment.date = validDate(); }

            if (validTime != false) { newAppointment.endTime = validTime(); }

            if (document.getElementById('medium').checked) { priority = medium.value; }

            else if (document.getElementById('low').checked) { priority = low.value; }

            else { priority = high.value; }

            newAppointment.priority = priority;

            if (validDate() === null | validDate() === undefined | validTime() === null | validTime() === undefined | validTime() === false | validDate() === false | isConcurrentAppointment(newAppointment.date,newAppointment.startTime,newAppointment.endTime) != true) {
                alert('Date or time entry invalid')
            }
            else {
                list.push(newAppointment);
                let tbody = document.getElementById("tbody");
                tbody.innerHTML += newAppointment.rowData();
            }
        }

        function validDate() {
            var inputDate = document.getElementById('date').value
            var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
            if (inputDate.match(dateformat)) {
                document.getElementById('date').focus();
                var opera1 = inputDate.split('/');
                var opera2 = inputDate.split('-');
                lopera1 = opera1.length;
                lopera2 = opera2.length;
                if (lopera1 > 1) {
                    var pdate = inputDate.split('/');
                }
                else if (lopera2 > 1) {
                    var pdate = inputDate.split('-');
                }
                var dd = parseInt(pdate[0]);
                var mm = parseInt(pdate[1]);
                var yy = parseInt(pdate[2]);
                years.push(yy);
                if (yy < MIN_YEAR) {
                    alert('Date is invalid.');
                    return error;
                }
                var daysInMonths = [31,28,31,30,31];
                if (mm == 1 || mm > 2) {
                    if (dd > daysInMonths[mm - 1]) {
                        alert('Date is invalid.');
                        return error;
                    }
                }
                if (mm == 2) {
                    var lyear = false;
                    if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
                        lyear = true;
                    }
                    if ((lyear == false) && (dd >= 29)) {
                        alert('Date is invalid');
                        return error;
                    }
                    if ((lyear == true) && (dd > 29)) {
                        alert('Date is invalid.');
                        return error;
                    }
                }
            }
            else {
                alert('Date is invalid.');
                document.getElementById('date').focus();
                return error;
            }
            return inputDate;
        }
        //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------      
        function validTime() {
            var startIndex = document.getElementById('startTime').selectedindex;
            var appStartTime = document.getElementById('startTime').options[startIndex].value;
            var endindex = document.getElementById('endTime').selectedindex;
            var endTime = document.getElementById('endTime').options[endindex].value;
            if (endTime <= appStartTime) {
                alert("Appointment must end later than the start time.");
                return error;
            }
            return endTime;
        }

        //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        function isConcurrentAppointment(dateInput,startInput,endInput) {
            var i;
            for (i = 0; i < list.length; i++) {
                if (dateInput == list[i].date) {
                    if (startInput.substring(0,3) == list[i].startTime.substring(0,3)
                        || startInput.substring(0,3) < list[i].startTime.substring(0,3) && endInput.substring(0,3) > list[i].endTime.substring(0,3) >= list[i].endTime.substring(0,3) > list[i].startTime.substring(0,3) && startInput.substring(0,3) < list[i].endTime.substring(0,3) && endTime.substring(0,3) <= list[i].endTime.substring(0,3) == list[i].endTime.substring(0,3)) {
                        alert('New appointments cannot start before prevIoUs one finishes');
                        return false
                    }
                    else
                        return true
                }
                else
                    return true
            }
            return true
        }

        //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //Tallying function:
        var i;

        //var yeararr = new Array(years[i]);

        function summary() {
            document.writeln('<table border="1">')
            document.writeln('<tr><th>Year</th><th>Count</th></tr>')
            for (i = 0; i < years.length; i++) {
                document.writeln('<tr><td>' + years[i] + '</td>'
                    + '<td>' + searchCount(years[i],years) + '</td></tr>')

            }
            document.writeln('</table>')


            function searchCount(targetValue,arr) {
                var count = 0; // Count of target value
                var i = 0;     // Iterative counter

                // examine each element.
                for (i = 0; i < arr.length; i++) {
                    if (arr[i] == targetValue)
                        count++;
                }
                return count;
            }
        }





    </script>

</head>




<body>

    <title>Diary</title>
    <h1 style="text-align: center;">Diary</h1>
    <form>
        <table bgcolor="#cccccc" cellpadding="5" cellspacing="0" align="center">
            <tr>
                <td align="right">Date</td>
                <td><input type="text" id="date" name="date" size="10"></td>
                <td align="right">Start Time</td>
                <td>
                    <select id="startTime">
                        <option value="08:00">08:00</option>
                        <option value="09:00">09:00</option>
                        <option value="10:00">10:00</option>
                        <option value="11:00">11:00</option>
                        <option value="12:00">12:00</option>
                        <option value="13:00">13:00</option>
                        <option value="14:00">14:00</option>
                        <option value="15:00">15:00</option>
                        <option value="16:00">16:00</option>
                        <option value="17:00">17:00</option>
                        <option value="18:00">18:00</option>
                    </select>
                </td>
                <td align="right">End Time</td>
                <td>
                    <select id="endTime">
                        <option value="08:00">08:00</option>
                        <option value="09:00">09:00</option>
                        <option value="10:00">10:00</option>
                        <option value="11:00">11:00</option>
                        <option value="12:00">12:00</option>
                        <option value="13:00">13:00</option>
                        <option value="14:00">14:00</option>
                        <option value="15:00">15:00</option>
                        <option value="16:00">16:00</option>
                        <option value="17:00">17:00</option>
                        <option value="18:00">18:00</option>
                    </select>
                </td>

            </tr>
            <tr>
                <td align="right">Subject:</td>
                <td><input type="text" id="subject" size="10"></td>
            </tr>
            <tr>
                <td align="right">Venue:</td>
                <td><input type="text" id="venue" size="10"></td>
            </tr>

            <tr>
                <td valign="top" align="center">Priority</td>
                <td><input type="radio" id="high" name="Priority" value="High" checked="true" /> High<br />
                <td><input type="radio" id="medium" name="Priority" value="Medium" /> Medium<br />
                <td><input type="radio" id="low" name="Priority" value="Low" /> Low<br />
                </td>
            </tr>
        </table>
        <tr>
            <div style="text-align:center;">
                <td></td>
                <td></td><input type="button" value="Add Appointment" onclick="addAppointment()" /></td>
            </div>
        </tr>


        <hr>

        <div>
            <table align="center" width="80%" height="150px" cellpadding="1px" cellspacing="1px" border="1" id="table1">
                <thead>
                    <tr>
                        <th width="50">Date</th>
                        <th width="20">Start</th>
                        <th width="20">End</th>
                        <th width="75">Subject</th>
                        <th width="60">Venue</th>
                        <th width="5">Priority</th>
                    </tr>
                </thead>
                <tbody id="tbody"> </tbody>
            </table>
        </div>
        <tr>
            <td></td>
            <div style="text-align:center;">
                <td></td><input type="reset" value="Randomise Appointments" onclick="shuffleAppointments()" /></td>
                <td></td><input type="button" value="Sort Appointments" onclick="sortRecords()" /></td>
                <td>by</td>
                <td>
                    <select id="Date">
                        <option value="date">Date</option>
                        <option value="startTime">Start Time</option>
                        <option value="endTime">End Time</option>
                        <option value="subject">Subject</option>
                        <option value="venue">Venue</option>
                        <option value="priority">Priority</option>
                    </select>
            </div>
            </td>
        </tr>
        <hr>




        <div style="text-align:left;">
            <td></td><input type="button" value="Summary" onclick="summary()" /></td>
            <td>by</td>
            <td>
                <select id="tallyOption">
                    <option value="year">Year</option>
                    <option value="date">Date</option>
                    <option value="optPriority">Priority</option>
                </select>
        </div>
        </hr>

    </form>

</body>

解决方法

您的问题似乎来自于在years函数中附加到validDate上,该函数在代码的其他地方被视为非变异函数。由于每次需要tha值时都会在validDate函数中重复调用addAppointment,因此years.push(yy)行也将被重复调用。您可以将years.push(yy)行移动到其他位置,但是更好的解决方案是更改addAppointment,以使其分别调用validDatevalidTime,存储它们的值,然后执行其余对存储值的操作。但是,您可能还希望移动years.push(yy),以便仅在约会完全有效时才调用它。

,

问题在于您每次都调用validDate()进行比较,并且在validDate函数内部对Years变量进行了变异。

有多种方法可以修复它,但我认为第一个也是最基本的一个(我强烈建议)是将validDate()的值存储在一个常量中,并对其进行进一步的比较。您应该始终避免每次都调用该函数。最好将其结果保存在内存中

您在哪里

            if (validDate() != false) { newAppointment.date = validDate(); }

在addApointment函数内部,只需

const isDateValid = validDate()

,然后用isDataValid替换所有validDate()即将发生的事件(5)

            const isDateValid = validDate()
            if (isDateValid != false) { newAppointment.date = isDateValid; }

and 

            if (isDateValid === null | isDateValid === undefined | validTime() === null | validTime() === undefined | validTime() === false | isDateValid === false | isConcurrentAppointment(newAppointment.date,newAppointment.startTime,newAppointment.endTime) != true) {
                alert('Date or time entry invalid')
            }

当然,我强烈建议您对有效时间做同样的事情。