簡體   English   中英

數組中的Javascript全局變量

[英]Javascript Global Variable in Array

我的問題對很多人來說可能很容易,但我是 Javascript 的新手。 我真的不知道以下代碼有什么問題。

var newValue = 1;
function getCurrentAmount() {

return [newValue,2,3];
}
var result = getCurrentAmount();
console.log(result[0] + "" + result[1] + result[2]);

上面代碼中,控制台顯示的結果是: undefined23 為什么結果不是“123”? 我正在嘗試使用全局變量,因為每次調用函數時我都想將 newValue 增加 1。 我想要類似以下內容:

var newValue = 1;
function getCurrentAmount() {
newValue ++;
return [newValue,2,3];
}
setInterval(function(){
   var result = getCurrentAmount();
    console.log(result[0] + "" + result[1] + result[2]);
}, 1000);

另外,我只是厭倦了以下代碼,它按預期工作。

    var newValue =1;
    function test() {
    newValue ++;
    return newValue;
}

console.log(test());

所以我認為問題出在數組上。

我希望我的問題足夠清楚。 提前致謝。

更好的方法應該是使用閉包newValue與全局范圍屏蔽 像這樣:

var getCurrentAmount = (function () {
    var newValue = 1; // newValue is defined here, hidden from the global scope
    return function() { // note: return an (anonymous) function
        newValue ++;
        return [newValue,2,3];
    };
)()); // execute the outer function
console.log(getCurrentAmount());

您可以像這樣實現“某種靜態”變量:

function getCurrentAmount() {
    var f = arguments.callee, newValue = f.staticVar || 0;
    newValue++;
    f.staticVar = newValue;
    return [newValue,2,3];
}

這應該比您的全局變量方法更有效。

您提供的代碼的行為與您預期的一樣,而不是您報告的那樣。 這是一個演示的jsfiddle

您必須在與您在問題中顯示的內容不同的上下文中設置newValue

這段代碼對我有用:

var newValue = 1;
function getCurrentAmount() {

return [newValue,2,3];
}
var result = getCurrentAmount();
console.log(result[0] + "" + result[1] + result[2]);

看看這里: http : //jsfiddle.net/PAfRA/

您說它不起作用的代碼實際上是有效的,請參閱工作演示,因此如果它對您不起作用,則可能您在全局范圍內沒有newValue變量(即在您的 js 文件的根目錄中,而不是在內部)任何其他功能)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM