简体   繁体   English

递增一次计数器,直到值大于if语句(Javascript)

[英]Increment a counter once until value is greater than if statement (Javascript)

I have the following code: 我有以下代码:

if (step < 1) {
    accSteps.push(parseInt(step));
}

for (i = 0; i < accSteps.length; i++) { 
    zOutput++;
    document.getElementById("zVal").innerHTML = zOutput;
}

The step variable is z co-ordinate from an mbed accelerometer to count number of steps. step变量是mbed加速度计的z坐标,用于计算步进数。 Currently, when the z-coordinate is < 1 (ie a step has been made), it will carry on adding steps to the counter until the z-coordinate is 1 or greater. 当前,当z坐标<1(即已执行一个步骤)时,它将对计数器进行添加步骤,直到z坐标为1或更大。 How do I increment by just 1 for the whole duration until z-coordinate is 1 or greater again? 如何在整个持续时间内仅增加1,直到z坐标再次为1或更大?

You need to set a flag for that. 您需要为此设置一个标志。

// Put this flag somewhere only executed once
var hasRegisteredStep = false;

if (step < 1 && hasRegisteredStep === false) {
    accSteps.push(parseInt(step));
    hasRegisteredStep = true;
} else if(step > 0) {
   hasRegisteredStep = false; // Reset the flag if greater than 0
}

for (i = 0; i < accSteps.length; i++) { 
    zOutput++;
    document.getElementById("zVal").innerHTML = zOutput;
}

Just add that condition in the for loop: 只需在for循环中添加该条件:

if (step < 1) {
        accSteps.push(parseInt(step));
    }
    for (i = 0; i < accSteps.length && step < 1; i++) { 
        zOutput++;
        document.getElementById("zVal").innerHTML = zOutput;
}

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

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