2012-11-28 60 views
1

我的問題可能很容易對很多人,但我是新來的Javascript。我真的不知道下面的代碼有什麼問題。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()); 

所以我認爲問題是關於數組。

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

+0

我得到'123'。你有其他可能會干擾的代碼嗎?這將是順便使用'globals'的正確方法。 – Halcyon

+0

我也在Chrome上獲得123.http://jsfiddle.net/D9VP4/ –

+1

代碼的順序與你的例子一樣嗎?當代碼的順序錯誤,或者沒有考慮onLoad或DOMReady事件時,有時會發生這種情況。 –

回答

2

更好的方法是通過使用關閉從全球範圍屏蔽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()); 
+0

我的問題是由無序造成的,有人在上面評論過它。然而,這裏沒有答案指出。我會接受你的答案作爲解決方案,因爲你教會了我另一個我不知道的好方法。感謝您的回答。 – Joey

0

您可以實現一個「之類的靜態的」變量,像這樣:

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

這應該不是你的全局變量的方法更好。

+0

這可以工作,但對'callee.staticVar'的依賴是_very_隱式的。最好使用閉包。 – Halcyon

0

您給出的代碼的行爲與您預期的相反,並非如您所報告的那樣。這是演示的jsfiddle

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

0

此代碼的工作對我來說:

var newValue = 1; 
function getCurrentAmount() { 

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

到這裏看看: http://jsfiddle.net/PAfRA/

0

你說這是行不通的它的實際工作,看工作demo,所以如果它的代碼不工作對你來說,你可能在全局範圍內沒有newValue變量(即在你的js文件的根目錄下,而不在其他任何函數內)。