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

时间:2018-01-15 11:51:36

标签: javascript

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

我有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

3 个答案:

答案 0 :(得分:4)

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

&#13;
&#13;
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);
    }
}
&#13;
<span id="number">this work</span><br />
<span id="miaonumber">this doesn't work</span>
&#13;
&#13;
&#13;

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

答案 1 :(得分:0)

问题是,您有一个数字并将其转换为字符串,然后再将其分配给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>

答案 2 :(得分:0)

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

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

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

(这也是最初使用8888.8889的原因,但在后续迭代中失败了。)

第一个版本有效,因为减法(而非加法/连接)将值强制转换为数字。