简体   繁体   中英

JS for loop not showing correct result

The question:

At exactly 10:25:21 , car speed is at 6.

11 mins later which is 10:36:21, car speed increased by 1, so is 7.

After 10:46:21 until 12:00:00, for every min, car speed increase steadily by 1, so is 8 onwards.

 <script> var date = new Date(); date.setHours(10); date.setMinutes(25); date.setSeconds(21); var speed; for (let i = 0; i < 95; i++) { if (i < 35) { speed = 6; } //increase speed by 1 after 10:36:21 else if (i < 45) { speed = 7; } // speed continously increase by 1 after 10:46:21 else { speed++; } date.setMinutes(25+i); document.write(date + ":" + speed + "m/s <br><br>"); } </script>

The result is showing me 6 till 10:59:21 instead of 10:36:21

And when the speed increased to 7, the hours and minutes increased too.

Any help is appreciated. I apologized if i'm a newbie here.

With

for (let i =  0; i < 95; i++) {

you are iterating over i which holds the amount of minutes - 25, because you started with 25 minutes.

if (i < 35) { 

will be true until the 35th loop (including).

You could just subtract your start value:

if (i < 10) { 
    speed = 6; 
} 
//increase speed by 1 after 10:36:21
else if (i < 20) 
{ speed = 7; 
} 

I think you have a problem with the amounts you are using, besides, here you have another idea:

var date = new Date();
date.setHours(10);
date.setMinutes(25);
date.setSeconds(21);

var speed; 
var dateToShow;

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

for (let i =  1; i < 96; i++) { 
    if (i < 11) { 
        speed = 6; 
    } 
    //increase speed by 1 after 10:36:21
    else if (i < 22) 
    { speed = 7; 
    } 
    // speed continously increase by 1 after 10:46:21
    else
    { speed++; 
    } 
    
    dateToShow = addMinutes(date, i); 

    document.write(dateToShow + ":" + speed + "m/s <br></br>")

}

I think this solves your problem.

I have added an extra function to add the minutes to a new date so you won't have more problems

The logic in the code is weird, to say the least.

Rather than use a counter to manually work through each minute, why not simply create dates that start and end the trip, and mark the two places where the speed increases:

 var startTime = new Date(); startTime.setHours(10); startTime.setMinutes(25); startTime.setSeconds(21); var endTime = new Date(); endTime.setHours(12); endTime.setMinutes(0); endTime.setSeconds(0); var time1 = new Date(); time1.setHours(10); time1.setMinutes(36); time1.setSeconds(21); var time2 = new Date(); time2.setHours(10); time2.setMinutes(46); time2.setSeconds(21); var thisTime = startTime; var speed = 0; while (thisTime < endTime) { if (thisTime < time1) { speed = 6; } else if (thisTime < time2) { speed = 7; } else { speed++; } document.write(thisTime + ":" + speed + "\\n<br>"); thisTime.setMinutes(thisTime.getMinutes() + 1); }

Using thisTime as the current time in the route, we just update that by 1 minute for each iteration. This is a while loop that runs from the start time to the end time, so as soon as thisTime is greater than endTime it ends the loop.

Before you start coding anything, you need to establish a few things first: Objects, Facts, Variables, States and Output

Objects :

1 What objects provide something that you need to use in your code?

2 What objects do you need to create in your code?

3 What objects do you need to manipulate in your code?

4 What objects are completely irrelevant to your code?

5 What will you do with any object used in your code?

Facts :

What are the known, static, facts?

What value or values will never change during the execution of the code but are required in the code?

Variables :

What are the unknowns?

What value or values will, or could, change during the execution of the code?

States :

1 What is the starting state of any object(s) or variable(s)?

2 What is desired/required final state of any object(s) or variable(s)?

Output :

1 Do you need to provide any "printed" output - eg, to the screen or the console?

2 Do you need to return anything - eg, is this a function that returns one or more values?


So, with this in mind, if we look at your question:

Objects :

There are two:

Car - completely irrelevant as nothing in the question is based on the type of vehicle, so we can ignore this object

Clock - required to determine the elapse of time in minutes. But, there is no need to create this as an object, a variable will handle this as we only actually need to know the time the clock would show. Presumbably, the car's clock or the driver's watch, for example, would be used to determine the time, but we are not looking at either as we have our own method of determining the time.

We could create a custom object for the car and its speed. However, the only value we would maintain on that object would be the speed. If, however, we needed to run the code for multiple vehicles, using different times, we could create an object for each. That is not required here as there is only one car. Likewise, the clock's value could be added to a car object, but, again, we only really need to know the time, not the fact that it is shown on a clock or that the clock/watch actually exists.

Facts :

There are six:

1 Start time

2 Speed change 1 time

3 Speed change 2 time

4 End time

5 We are checking the speed every minute

6 The speed is dependant on the time

The four times are static values, so we can create variables to hold these values and nothing in the code will change these values. Often, these are created using const but I've used var in my code example.

The fact that we are checking/changing the speed every minute just provides us with a reason to pinpoint particular times between the start and end times. A variable is required to handle this as the current time value will change during the running of the code.

States :

There are two initial states:

1 The time starts at 10:25:21

2 We start driving at 6mph

There is one final state:

The time stops at 12:00:00

Note that the speed will be whatever the code has calculated, so has an unknown final state

Output :

In this case, the output is written into the document. When testing, it is more usual to output to the console, using console.log(...)


Given all that, we can look at what code is required.

1 Create the static variables - the four points in time

2 Create the other variables - the speed and the current time

3 Create a loop that will move us through time from the "Start time" to the "End time", one minute at a time, using the current time variable to keep track of where we are

4 Create if/else tests to determine what the current time is in relation to the static times

5 Determine what speed the car should be going at that time

6 Output the time and speed - as we are not in a function, we output to either the page or the console as desired as we are not returning a value to other code

7 End the loop once "End time" is reached.

There are three types of loops we could use:

1 a for loop - this is normally used to iterate over collections, by referencing the collection's items by index number, or to provide a counter that can be used within the loop. As we don't need a counter and don't have a collection, we won't use this

2 a while loop - this is not dependant on counters, it simply tests a condition statement before starting an iteration of the loop. If the test fails, the condition is not met and the loop doesn't run.

3 a do/while loop - similar to a while loop except that the condition is checked AFTER the first iteration, so will run at least once. If the condition is met, the loop starts again. We could use this as we know that the loop needs to run at least once. However, if the current time was already after the end time, we would not want the loop to run, so I have avoided this loop

There are other types of loops available, such as for/in , for/of and forEach but these are generally used for objects and collections, so are not relevant here.

Thus, the best loop to use is the while loop as the requirement is to "...do something until..."

So, now we know all we need to know to construct the code.

// Create the static time variables
// Start time
var startTime = new Date();
startTime.setHours(10);
startTime.setMinutes(25);
startTime.setSeconds(21);

// Speed change 1 time
var endTime = new Date();
endTime.setHours(12);
endTime.setMinutes(0);
endTime.setSeconds(0);

// Speed change 2 time
var time1 = new Date();
time1.setHours(10);
time1.setMinutes(36);
time1.setSeconds(21);

// End time
var time2 = new Date();
time2.setHours(10);
time2.setMinutes(46);
time2.setSeconds(21);

// Create the other variables
// "thisTime" is initially set to "startTime" but will be incremented by the loop code
var thisTime = startTime;
// A variable to hold the current speed through the loops
// This could be set to 6, but if the loops don't run (ie, the condition is not met), we would not want the speed to be 6
var speed = 0; 

// Start a loop - check that the current time (thisTime) is less than the endTime
while (thisTime < endTime) {
  // If it is, check if we have reached the first speed change time - "time1"
  if (thisTime < time1) {
    // If we haven't, keep the speed at 6
    speed = 6;
    // If we have, check if we have reached the second speed change time - "time2"
  } else if (thisTime < time2) {
    // If we haven't, the speed is 7
    speed = 7;
    // If we have, we can now increase the speed 1mph for each minute (ie, for all further iterations of the loop)
  } else {
    speed++;
  }
  // Output the time and speed
  document.write(thisTime + ":" + speed + "\n<br>");
  // Add one minute to the thisTime variable which will be tested at the start of the next iteration of the loop
  thisTime.setMinutes(thisTime.getMinutes() + 1);
}

And, to convert this all back into English:

Given these four points in time and checking my speed every minute, I start driving at the first time point. If I've not reached the second time point, I'm doing 6mph. But, if I have reached that, but haven't yet reached the third time point, I'm doing 7mph. But if I've reached that, I keep increasing my speed by 1mph for every minute. I stop driving at the final time point. Throughout, I'm making a note of the time and my speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM