繁体   English   中英

函数是否可以像局部变量一样很好地使用全局变量?

[英]Does function work with global variables so well like local variables?

当我将所有变量( box2displaytotalerror )放置在函数中时,代码将起作用,但是当我将其放置在函数外部时,它将无法工作。 我想它应该起作用,因为所有这四个变量都是全局变量,并且函数必须识别它们(变量)。 请让我高兴的是,有人可以出来解释为什么代码不起作用。

 var box1 = document.getElementById("box1").value; var box2 = document.getElementById("box2").value; var display = document.getElementById("display"); var total = Number(box1) + Number(box2); var error = "There is a problem with the input fields"; function cal() { if (!isNaN(box1) && !isNaN(box2)) { display.innerHTML = "$" + total; } else { display.innerHTML = error; } } 
 <h1>Best Addiction Calculator</h1> <input class="field" placeholder="type first number" type="text" id="box1"> <input class="field" placeholder="type second number" type="text" id="box2"> <button style="font-size:xx-large; color:#860EED" onClick="cal()">Calculate</button> <p id="display">i</p> 

谢谢大家!

问题不在于其中的变量是, 你设置的值是。

这段代码:

var box1 = document.getElementById("box1").value;
var box2 = document.getElementById("box2").value;

运行时从输入中读取值。 您想在用户单击按钮时读取其值。

可以这样做,但这不合理:

// JUST AN EXAMPLE, DON'T ACTUALLY DO IT
var box1;
var box2;
var display;
var total;
var error;

function cal() {
    box1 = document.getElementById("box1").value;
    box2 = document.getElementById("box2").value;
    display = document.getElementById("display");
    total = Number(box1) + Number(box2);
    error = "There is a problem with the input fields";

    if (!isNaN(box1) && !isNaN(box2)) {
        display.innerHTML = "$" + total;
    } else {
        display.innerHTML = error;
    }
}

这表明问题不在于变量在哪里,而在于设置变量的值时。

但是如果没有充分的理由就不会这样做 由于没有理由将这些变量放在函数外部,因此请将它们放在函数中。 通常,给变量一个最窄的范围。

如果查找元素是您只想执行一次的昂贵操作(不是, getElementById并非如此之快),则可以查找元素一次,然后在cal获取它们的值:

var box1 = document.getElementById("box1");              // Note no `.value` here
var box2 = document.getElementById("box2");              // Or here
var display = document.getElementById("display");

function cal() {
    var total = Number(box1.value) + Number(box2.value); // Note change on this line
    var error = "There is a problem with the input fields";

    if (!isNaN(box1) && !isNaN(box2)) {
        display.innerHTML = "$" + total;
    } else {
        display.innerHTML = error;
    }
}

暂无
暂无

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

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