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>
4

2 回答 2

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>
于 2013-07-27T21:47:13.223 回答
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.");
        }

    };

}());
于 2013-07-27T21:48:28.280 回答