简体   繁体   English

增加和减少一个变量,直到在 Javascript 中达到一个数字

[英]Increase and decrease a variable until a number is reached in Javascript

How can I increase and decrease a variable in Javascript until 100 and when 100 is reached it should start decreasing.如何在 Javascript 中增加和减少变量直到 100,当达到 100 时它应该开始减少。

So accuracyBarValue should start in 0, increase to 100, and when 100 is reached it should go to 0, and then repeat procedure.所以accuracyBarValue应该从0开始,增加到100,当达到100时它应该去0,然后重复这个过程。

This in intervals of 10.这以 10 为间隔。

I use this in a very simple JS game, where this value is used to increase and decrease a PowerBar.我在一个非常简单的 JS 游戏中使用它,该值用于增加和减少 PowerBar。

Here is another take on this:这是另一种看法:

 var up = true; var value = 0; var increment = 10; var ceiling = 100; function PerformCalc() { if (up == true && value <= ceiling) { value += increment if (value == ceiling) { up = false; } } else { up = false value -= increment; if (value == 0) { up = true; } } document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />'; } setInterval(PerformCalc, 1000);
 <div id="counter"></div>

for (var i=0;i<100;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
while (i>0)
{
    i -= 10;
    document.write("The number is " + i);
    document.write("<br />");
}

You can test and modify it here .您可以在此处对其进行测试和修改。

Code代码

let i = 100;
setInterval(() => {
  console.log(Math.abs((i+=10)%200 - 100))
}, 1000);

Deconstruction解构

  1. i+=10i gets indefinitely increased by 10 on every tick i+=10i在每个刻度上无限增加 10
  2. %100 → modulo of double the max value (division remaining ex. 10 % 6 = 4 ) %100 → 最大值两倍的模数(除法剩余,例如10 % 6 = 4
  3. - 100 → remove the range (so the numbers will always be between 100 and -100, otherwise it would be between 0 and 6) - 100 → 删除范围(因此数字将始终在 100 和 -100 之间,否则将在 0 和 6 之间)
  4. Math.abs() → removes the - (Makes sure the number moves from 0 to 100 and back) Math.abs() → 删除 -(确保数字从 0 移动到 100 并返回)

Steps Visualized步骤可视化

i++我++

∞       .
       .
      .
     /
    /
   / 
  /
0

(i+=10)%200 (i+=10)%200

200 
     /    /    /    .
    /    /    /    .
   /    /    /    .
  /    /    /    /
 /    /    /    /
0

i++%200-100 i++%200-100

100 
  \        /\        /\
   \      /  \      /  \
0   \    /    \    /    .
     \  /      \  /      .
      \/        \/        .
-100

Math.abs(i++%200-100) Math.abs(i++%200-100)

100 
  \    /\    /.
   \  /  \  /  .
    \/    \/    .
0

Implementation Example实现示例

 const max = 10; let i = max; const $body = document.querySelector('body'); setInterval(() => { const val = Math.abs(i++%(max * 2) - max); const $el = document.createElement('i'); $el.style = `--i: ${i}; --val: ${val}`; $body.appendChild($el); window.scrollTo(window.innerWidth, 0); console.log(val); }, 200);
 i { --i: 0; --val: 0; --size: 10px; position: absolute; background: black; width: var(--size); height: var(--size); top: var(--size); left: calc(-10 * var(--size)); transform: translate( calc(var(--i) * var(--size)), calc(var(--val) * var(--size)) ) }

Alternative Approaches (Float based)替代方法(基于浮动)

Math.acos(Math.cos(i * Math.PI)) / Math.PI;

or或者


Math.abs(i - Math.floor(i) - .5);

Where i is a float between 0 - Infinity .其中i0 - Infinity之间的float Result is a float as well that needs to be multiplied by your max and rounded (target value).结果也是一个float ,需要乘以最大值并四舍五入(目标值)。

Using Duration and Frame Rate.使用持续时间和帧速率。

Another approach that allows you to specify the duration and frame rate.另一种允许您指定持续时间和帧速率的方法。 Highly useful for animations and things that happen over a period of time.对于动画和一段时间内发生的事情非常有用。

HTML HTML

<h2>Increment Value over a Duration with a given framerate</h2>
Value: <span id="value">0</span>

JavaScript JavaScript

var valueElement = document.getElementById('value');

var start     = 0;
var end       = 100;
var duration  = 10000; // In milliseconds (divide by 1000 to get seconds).
var framerate = 50;    // In milliseconds (divide by 1000 to get seconds).

var toAdd = ( ( end - start ) * framerate ) / duration;

var interval = setInterval(function() {
    var currentValue = parseFloat(valueElement.innerHTML);

  if (currentValue >= end) {
      clearInterval(interval);
    return;
  }

    valueElement.innerHTML = (!isNaN(currentValue) == true ? currentValue + toAdd : toAdd);
}, framerate);

JSFiddle JSFiddle

https://jsfiddle.net/joshuapinter/8uasm7ko/ https://jsfiddle.net/joshuapinter/8uasm7ko/

I wanted to display the incremental value but you could easily wrap this up into a generic function as well.我想显示增量值,但您也可以轻松地将其包装为通用函数。

var i = 0;
while( i < 100 )
{
    i++;
}

while( i > -1 )
{
    i--;
}

You can also do other code in the while loops, obviously.显然,您还可以在while循环中执行其他代码。

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

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