gpt4 book ai didi

javascript - 推送到数组的值不会保留

转载 作者:行者123 更新时间:2023-11-28 08:59:47 25 4
gpt4 key购买 nike

我想将一个值推到数组的末尾,但由于某种原因它不起作用。当我单击按钮时,它应该将值添加到数组的末尾。然后,如果我再次单击它,它应该告诉我它仍然在那里,但它只是不断插入数组。如何获取保留在数组中的值。

    <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 时,都会从头开始重新构建数组 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.");
}

};

}());

关于javascript - 推送到数组的值不会保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17902727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com