我正在尝试编写一个按钮,单击该按钮时,会调用一个函数,该函数将新元素添加(追加)到数组中,然后该元素会打印到屏幕上。在本例中,我尝试将新单词添加到现有的单词列表中。我遇到了几个问题:
如何在页面上打印数组,如下所示:( /image/Rfk2V.jpg )。我是否只需编写几个带有换行符的新段落标签即可显示数组的元素?
我的按钮似乎存在根本问题。它不仅没有做我想要它做的事情,而且甚至不会显示“尝试一下!”我想要的文本。
addToArray 函数在调用时不会执行。不管是在错误的地方还是我写的函数在语法上完全错误,我不知道。
这是我到目前为止所拥有的:
<h1>Adding elements onto the end of an array:</h1>
<p>Click the button below to append more values to the array!</p>
<button id="btnAdd" value="Try it!" onclick="addFruitOnClick()"/>
<script type = "text/javascript">
var foods = [];
foods[0] = "Banana";
foods[1] = "Orange";
foods[2] = "Apple";
foods[3] = "Mango";
foods[4] = "Lemon";
var i = 0;
while (i < foods.length) {
document.write(foods[i] + "<br />");
}
function addFruitOnClick() { // Define first function
document.write("hi");
}
function addToArray() { // Define what the second function's task is
foods.concat([ // Using (array.concat) to append to existing array
"dragonfruit",
"Cherry",
"Lime",
"Strawberry"
]);
}
} // End of addToArray
addtoArray ();
</script>
我遗漏了我的 head/body/html 标签,但这就是它的要点。如有任何帮助,我们将不胜感激。
最佳答案
我对 concat 和 addFruitOnClick 函数的代码进行了一些修改。
var foods = [];
foods[0] = "Banana";
foods[1] = "Orange";
foods[2] = "Apple";
foods[3] = "Mango";
foods[4] = "Lemon";
function display(){
var i = 0;
while (i < foods.length) {
document.write(foods[i++] + "<br />");
}
document.write("<br />");
}
function addFruitOnClick(fruit) { // Define first function
foods.push(fruit);
}
function addToArray() { // Define what the second function's task is
foods = foods.concat([ // Using (array.concat) to append to existin array
"dragonfruit",
"Cherry",
"Lime",
"Strawberry"
]);
} // End of addToArray
display();
addFruitOnClick("Cherry");
display();
addToArray ();
display();
关于javascript - 向数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43313790/