【问题标题】:Adding numbers instead of adding increment添加数字而不是添加增量
【发布时间】:2017-10-14 12:44:38
【问题描述】:

我有一个小脚本,可以在给定时间段内按数字递增数字。如果增加一个 value++ 有效,如果我想添加由 math.random 函数生成的类型的另一个值而不是添加,请添加到现有值。我怎样才能改变这个?我希望生成的数字添加到 innerHTML 中的现有值。

document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);

nowResources = function() {
  document.getElementById("data-gen").innerHTML += Math.floor((Math.random() * 10) + 1);
  setTimeout(nowResources, 1000);
}

nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>

【问题讨论】:

标签: javascript increment


【解决方案1】:

您将数字附加到字符串。将您的innerHTML 转换为带有parseInt 的数字,它会按您的预期工作。

document.getElementById("data-gen").innerText = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);

nowResources = function() {
  // parseInt( yourString, radix )
  const num = parseInt( document.getElementById("data-gen").innerText, 10 );
  document.getElementById("data-gen").innerText = num + Math.floor((Math.random() * 10) + 1);
  setTimeout(nowResources, 1000);
}

nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>

但一个缺点是,您每次想要更改 DOM 时都在查询它。最好将您的号码存储在超时之外,并使用如下间隔:

let num = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);

document.getElementById("data-gen").innerText = num;
nowResources = function() {
  num += Math.floor((Math.random() * 10) + 1);
  document.getElementById("data-gen").innerText = num;
}

setInterval( nowResources, 1000 );
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>

这样你就不需要在每次迭代时解析你的数字。

【讨论】:

  • 非常感谢 - 我以为就是这样,但正如您所见,必须有人让我意识到这一点。我会在几分钟内说你最好的。
【解决方案2】:

当您使用 + 时,它将作为字符串并连接为字符串,使用 parseInt 将其转换为整数

  document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));

演示

document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1)+ Math.floor((Math.random() * 100) + 1);

nowResources = function() {
  document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
  setTimeout(nowResources, 1000);
}

nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>

【讨论】:

  • 你不认为那里有重复,因为这是一个非常简单且可能经常被问到的问题吗?
【解决方案3】:

为了保持逻辑清晰,只需使用一个局部变量来存储值,无需通过parseInt 进行反向转换和令人厌烦(且昂贵且混乱)的 DOM 元素方法跳舞:

var value = 0;

function setValue(addValue) {
    value += addValue;
    document.getElementById("data-gen").innerHTML = value;
}

nowResources = function() {
  setValue(Math.floor((Math.random() * 10) + 1))
  setTimeout(nowResources, 1000);
}

nowResources();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 2014-05-31
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多