简体   繁体   English

JS for 循环没有显示正确的结果

[英]JS for loop not showing correct result

The question:问题:

At exactly 10:25:21 , car speed is at 6.恰好在 10:25:21 ,汽车速度为 6。

11 mins later which is 10:36:21, car speed increased by 1, so is 7. 11分钟后即10点36分21秒,车速增加1,也增加7。

After 10:46:21 until 12:00:00, for every min, car speed increase steadily by 1, so is 8 onwards. 10:46:21后至12:00:00,每分钟,车速稳定增加1,8以后也是如此。

 <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结果显示 6 到 10:59:21 而不是 10:36:21

And when the speed increased to 7, the hours and minutes increased too.当速度增加到7时,小时和分钟也增加了。

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.您正在迭代i ,其中包含分钟数 - 25,因为您从 25 分钟开始。

if (i < 35) { 

will be true until the 35th loop (including).将在第 35 个循环(包括)之前为真。

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.使用thisTime作为路由中的当前时间,我们只需为每次迭代更新 1 分钟。 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.这是一个从开始时间到结束时间运行的while循环,因此只要thisTime大于endTime它就会结束循环。

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? 1 哪些对象提供了您需要在代码中使用的东西?

2 What objects do you need to create in your code? 2 您需要在代码中创建哪些对象?

3 What objects do you need to manipulate in your code? 3 您需要在代码中操作哪些对象?

4 What objects are completely irrelevant to your code? 4 哪些对象与您的代码完全无关?

5 What will you do with any object used in your code? 5 您将如何处理代码中使用的任何对象?

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)? 1 任何对象或变量的起始状态是什么?

2 What is desired/required final state of any object(s) or variable(s)? 2 任何对象或变量的期望/要求的最终状态是什么?

Output :输出

1 Do you need to provide any "printed" output - eg, to the screen or the console? 1 您是否需要提供任何“打印”输出 - 例如,到屏幕或控制台?

2 Do you need to return anything - eg, is this a function that returns one or more values? 2 你是否需要返回任何东西——例如,这是一个返回一个或多个值的函数吗?


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 1 开始时间

2 Speed change 1 time 2 变速 1 次

3 Speed change 2 time 3 变速 2 次

4 End time 4 结束时间

5 We are checking the speed every minute 5 我们每分钟都在检查速度

6 The speed is dependant on the time 6 速度取决于时间

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.通常,这些是使用const创建的,但我在我的代码示例中使用了var

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 1 时间从10:25:21开始

2 We start driving at 6mph 2 我们开始以每小时 6 英里的速度行驶

There is one final state:有一个最终状态:

The time stops at 12:00:00时间停止在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(...)测试时,更常用的是输出到控制台,使用console.log(...)


Given all that, we can look at what code is required.鉴于所有这些,我们可以看看需要什么代码。

1 Create the static variables - the four points in time 1 创建静态变量——四个时间点

2 Create the other variables - the speed and the current time 2 创建其他变量 - 速度和当前时间

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 3 创建一个循环,将我们从“开始时间”移动到“结束时间”,每次一分钟,使用当前时间变量来跟踪我们所处的位置

4 Create if/else tests to determine what the current time is in relation to the static times 4 创建 if/else 测试以确定当前时间与静态时间的关系

5 Determine what speed the car should be going at that time 5 确定当时汽车应该以什么速度行驶

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 6 输出时间和速度 - 因为我们不在函数中,所以我们根据需要输出到页面或控制台,因为我们没有向其他代码返回值

7 End the loop once "End time" is reached. 7 到达“结束时间”后结束循环。

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. 1 a for循环 - 这通常用于迭代集合,通过按索引号引用集合的项目,或提供可在循环内使用的计数器。 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. 2 while循环 - 这不依赖于计数器,它只是在开始循环迭代之前测试条件语句。 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. 3 do/while循环 - 类似于while循环,不同之处在于在第一次迭代后检查条件,因此将至少运行一次。 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.还有其他类型的循环可用,例如for/infor/offorEach但这些通常用于对象和集合,因此这里不相关。

Thus, the best loop to use is the while loop as the requirement is to "...do something until..."因此,最好使用的循环是while循环,因为要求是“...做某事直到...”

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.如果我还没有到达第二个时间点,我的速度是 6mph。 But, if I have reached that, but haven't yet reached the third time point, I'm doing 7mph.但是,如果我已经达到了那个,但还没有达到第三个时间点,我的速度是 7mph。 But if I've reached that, I keep increasing my speed by 1mph for every minute.但如果我已经达到了,我会每分钟以 1 英里/小时的速度增加速度。 I stop driving at the final time point.我在最后一个时间点停止开车。 Throughout, I'm making a note of the time and my speed.在整个过程中,我都会记下时间和速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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