减法运算符工作,但加法运算符不起作用



我一直在查看有关操作员不工作的一些主题,但无法解决我的问题。

我有 2 个 JavaScript 代码。

<span id="number">this work</span>
<span id="miaonumber">this doesn't work</span>
<script>
    setTimeout(start, 1000);
    var hh = 9999.9999;
    var num = document.getElementById('number');
    function start() {
        setInterval(increase, 1000);
        }
    function increase() {
        if (hh > 0.0001) {
            hh = (hh-0.0001).toFixed(15);
            num.innerText = hh;
        }
    }
    setTimeout(startmiao, 1000);
    var zz = 8888.8888;
    var nummiao = document.getElementById('miaonumber');
    function startmiao() {
        setInterval(increasemiao, 1000);
    }
    function increasemiao() {
        if (zz > 0) {
            zz = (zz+0.0001).toFixed(15);
            nummiao.innerText = zz;
        }
    }
</script>

<span id="number"></span>会起作用,但<span id="miaonumber"></span>不起作用,我打开 F12 查看,每秒 +1 错误Uncaught TypeError: (zz + 0.0001).toFixed is not a function

使用 .toFixed() 时,您将 hh 和 zz 转换为字符串。 如果你把它们保留为数字,那么它们都有效。 只需将.toFixed()移动到设置元素文本的位置即可。

setTimeout(start, 1000);
var hh = 9999.9999;
var num = document.getElementById('number');
function start() {
    setInterval(increase, 1000);
    }
function increase() {
    if (hh > 0.0001) {
        hh = hh - 0.0001;
        num.innerText = hh.toFixed(15);
    }
}
setTimeout(startmiao, 1000);
var zz = 8888.8888;
var nummiao = document.getElementById('miaonumber');
function startmiao() {
    setInterval(increasemiao, 1000);
}
function increasemiao() {
    if (zz > 0) {
        zz = zz + 0.0001;
        nummiao.innerText = zz.toFixed(15);
    }
}
<span id="number">this work</span><br />
<span id="miaonumber">this doesn't work</span>

Javascript足够明智,知道当你减去值时,你很可能希望它们是数字,所以"123" - 1 == 122,但是当你尝试添加它时,假设你想附加到现有的字符串,所以"123" + 1 == "1231"

问题是,你有一个数字并将其转换为字符串,然后你再次将其分配给zz。然后你添加一个数字,但是当zz是一个字符串时,你会得到一个字符串,而字符串没有方法toString .

解决方案:仅将字符串值分配给输出,而不分配给zz

function start() {
    setInterval(increase, 1000);
}
function increase() {
    if (hh > 0.0001) {
        hh = (hh - 0.0001).toFixed(15);
        num.innerText = hh;
    }
}
function startmiao() {
    setInterval(increasemiao, 1000);
}
function increasemiao() {
    if (zz > 0) {
        zz += 0.0001;
        nummiao.innerText = zz.toFixed(15);
    }
}
var hh = 9999.9999,
    num = document.getElementById('number'),
    zz = 8888.8888,
    nummiao = document.getElementById('miaonumber');
setTimeout(start, 1000);
setTimeout(startmiao, 1000);
<span id="number">this work</span>
<span id="miaonumber">this doesn't work</span>

toFixed从数值中获取字符串值。然后,当您尝试将+与此字符串值一起使用时,它默认为连接文本,而不是加法。此新文本不再具有toFixed方法。

仅在显示值时使用toFixed,以便zz保持数字:

function increasemiao() {
    if (zz > 0) {
        zz = (zz+0.0001);
        nummiao.innerText = zz.toFixed(15);
    }
}

(这也是为什么它最初使用 8888.8889 工作,但在后续迭代中失败的原因。

第一个版本之所以有效,是因为减法(而不是加法/串联(将值强制为数字。

最新更新