Javascript 推送到数组的值赢得';我不能留下来
我想将一个值推送到数组的末尾,但由于某种原因它不起作用。当我单击按钮时,它应该将值添加到数组的末尾。然后,如果我再次单击它,它会告诉我它仍然在那里,但它只是继续推进数组。如何获取值以保留在数组中Javascript 推送到数组的值赢得';我不能留下来,javascript,Javascript,我想将一个值推送到数组的末尾,但由于某种原因它不起作用。当我单击按钮时,它应该将值添加到数组的末尾。然后,如果我再次单击它,它会告诉我它仍然在那里,但它只是继续推进数组。如何获取值以保留在数组中 <html> <head> <script> function myFunction() { var asdf = ["a","b","c","e"];
<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>
函数myFunction(){
var asdf=[“a”、“b”、“c”、“e”];
如果(asdf.indexOf(“d”)=-1){
asdf.push(“d”);
警报(asdf.indexOf(“d”)+“它已被推到末尾。”);
}否则{
警报(asdf.indexOf(“d”)+“它仍然在那里。”);
}
}
这是因为您在函数内部本地声明了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>
window.asdf=[“a”、“b”、“c”、“e”];
函数myFunction(){
if(window.asdf.indexOf(“d”)=-1){
window.asdf.push(“d”);
警报(window.asdf.indexOf(“d”)+“它已被推到末尾。”);
}否则{
警报(window.asdf.indexOf(“d”)+“它仍然在那里。”);
}
}
每次调用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.");
}
};
}());
虽然这是可行的,但使用全局变量是一个不好的习惯。@JeremyJStarcher-我完全同意,我的回答假设了提供的简单情况。任何解决方案都将以全局变量为基础,因为变量的状态需要在函数外部维护。这是一个干净的解决方案,不使用全局搜索。@JeremyJStarcher是的,我看到了。有趣的解决方案,尽管我不喜欢静态,就像我不喜欢全局一样:p然后把它们看作是私有的。在这种情况下,也是一样的。谢谢。我早该抓到的。