2013-07-27 34 views
1

我想將值推到數組的末尾,但由於某種原因它不工作。當我點擊按鈕時,它應該將值添加到數組的末尾。然後,如果我再次點擊它,它應該告訴我,它仍然存在,但它只是推着陣列。我如何獲得值留在陣列中。推送到數組的值不會保留

<html> 
    <head> 
     <script> 
      function myFunction() { 
       var asdf = ["a","b","c","e"]; 
       if (asdf.indexOf("d")==-1) { 
        asdf.push("d"); 
        alert(asdf.indexOf("d")+"It has been pushed to the end."); 
       } else { 
        alert(asdf.indexOf("d")+"It is still there."); 
       } 
      } 
     </script> 
    </head> 
    <body> 
     <input type="button" onclick="myFunction()" value="Show alert"> 
    </body> 
    </html> 

回答

0

每次調用myFunction的時候,你的陣列asdf是從頭開始了。

像這樣的工作:

var myFunction = (function() { 
    // This line is only run once. 
    var asdf = ["a", "b", "c", "e"]; 

    // This is run with every call to myFunction, and will reuse the array 
    return function() { 
     if (asdf.indexOf("d") == -1) { 
      asdf.push("d"); 
      alert(asdf.indexOf("d") + "It has been pushed to the end."); 
     } else { 
      alert(asdf.indexOf("d") + "It is still there."); 
     } 

    }; 

}()); 
+0

謝謝。我應該抓住那個。 – Brunus

0

這是因爲你在函數內部本地聲明瞭asdf。所以當功能完成時,asdf變量被刪除,然後在下次單擊按鈕時重新創建。相反,你需要使它全球:

<html> 
<head> 
    <script> 
     window.asdf = ["a","b","c","e"]; 
     function myFunction() { 
      if (window.asdf.indexOf("d")==-1) { 
       window.asdf.push("d"); 
       alert(window.asdf.indexOf("d")+"It has been pushed to the end."); 
      } else { 
       alert(window.asdf.indexOf("d")+"It is still there."); 
      } 
     } 
    </script> 
</head> 
<body> 
    <input type="button" onclick="myFunction()" value="Show alert"> 
</body> 
</html> 
+0

雖然這樣的作品,使用全局變量是一個壞習慣進入。 –

+0

@JeremyJStarcher - 我完全同意,我的答案假設提供了簡單的情況。任何解決方案都將圍繞以全局變量爲基礎進行,儘管變量的狀態需要在函數之外進行維護。 –

+0

查看我的答案,以獲得一種常見模式,以在JavaScript中創建靜態變量。這是一個乾淨的解決方案,不使用全局。 –