2013-07-27 29 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中创建静态变量。这是一个干净的解决方案,不使用全局。 –