簡體   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