javascript - 向数组添加新元素

标签 javascript html

我正在尝试编写一个按钮,单击该按钮时,会调用一个函数,该函数将新元素添加(追加)到数组中,然后该元素会打印到屏幕上。在本例中,我尝试将新单词添加到现有的单词列表中。我遇到了几个问题:

  1. 如何在页面上打印数组,如下所示:( /image/Rfk2V.jpg )。我是否只需编写几个带有换行符的新段落标签即可显示数组的元素?

  2. 我的按钮似乎存在根本问题。它不仅没有做我想要它做的事情,而且甚至不会显示“尝试一下!”我想要的文本。

  3. 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/

相关文章:

javascript - 如何将数据库/表数据转换为文件名?

javascript - 从 iframe 标签获取嵌入的 youtube 播放列表视频的当前时间戳

javascript - jQuery 结构 - 澄清?

javascript - 使用 jquery 显示和隐藏叠加层

javascript - 如何将在 for 循环中选中的复选框中的数组值推送到另一个数组?

javascript - 将控制台日志结果打印到一个 div 类的多个实例

html - div 未显示,但其内容是

html - brightness() 函数和 preserve-3d 不能一起工作

javascript - 相同的 chrome 对象 ID 是否意味着堆分析器中的对象相同?

javascript - 在javascript中执行命令