我想将值推送到数组的末尾,但由于某种原因它不起作用。当我单击按钮时,它应该将值添加到数组的末尾。然后,如果我再次点击它,它应该告诉我它仍然存在,但它只是保持pushin到阵列。如何将值保留在数组中。
<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 :(得分: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>
答案 1 :(得分: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.");
}
};
}());