向数组中添加新元素。

时间:2022-01-14 15:41:29

I am trying to write a button that when clicked, calls a function that adds (appends) a new element to an array, and the element then gets printed out onto the screen. In this case, I am trying to add new words to an already existing list of words. I'm having several problems:

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

  1. How to get the array to print out on a page like this: (https://imgur.com/a/He4vK). Do I just write several new paragraph tags with line breaks to have the elements of the array show up?

    如何让数组在这样的页面上打印出来:(https://imgur.com/a/He4vK)。我是否只是用换行符写了几个新的段落标签,以使数组元素出现?

  2. There seems to be something fundamentally wrong with my button. It not only doesn't do what I want it to do, but it won't even display the "Try it!" text that I want it to.

    我的按钮好像有什么毛病。它不仅不能做我想要做的事情,而且它甚至不会显示我想要的“Try It !”

  3. The addToArray function won't execute when it's called. Whether it's in the wrong place or the function I wrote just is completely wrong syntactically, I have no clue.

    addToArray函数在调用时不会执行。不管是在错误的地方还是我写的函数完全错误的语法,我没有线索。

Here's what I have so far:

以下是我目前所拥有的:

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

I left out my head/body/html tags but that's the jist of it. Any help is appreciated.

我忘记了我的头/身体/html标签,但那是它的精髓。任何帮助都是感激。

4 个解决方案

#1


0  

I did some modifications of your code for concat and addFruitOnClick function.

我为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();

#2


0  

First, at the end of your script, you should call addToArray(), not addtoArray() (case matters)

首先,在脚本的末尾,应该调用addToArray(),而不是addToArray() (case事项)

Next, the function concat does not update your array in place, you should write

接下来,函数concat不会更新您的数组,您应该编写。

foods = foods.concat([ "dragonfruit", "Cherry" /* ... */ ])

or

[ "dragonfruit", "Cherry" /* ... */ ].forEach(function(fruit){ food.push(fruit) })

Then your code won't run forever anymore.

然后你的代码就不会再运行了。

#3


0  

I slightly changed your code - you can play with the concept to mould it to your needs - basically there is a single array of fruits and this is shown as dynamically created list.

我稍微改变了您的代码——您可以使用这个概念来对您的需求进行建模——基本上有一个单一的水果数组,这是动态创建的列表。

I then have a series of buttons that call a function to add a specific food to the array.

然后,我有一系列按钮,调用一个函数来向数组添加特定的食物。

Clicking an ad button - allows a new fruit to be added to the array and then all you have to do is re-render the lest to show the new content. This could be amended to remove fruits as well:

单击一个广告按钮——允许将一个新水果添加到数组中,然后你所要做的就是重新呈现,以免显示新的内容。这也可以修改,以去除水果:

var foods = ["Banana", "Orange","Apple", "Mango","Lemon"]

showFoods();

function showFoods() {
  var str= '';
  
  foods.forEach(function(food) {
    str += '<li>' + food + '</li>';
   });
   
  document.getElementById('foods').innerHTML = str;
 }

function addFood(food){
  foods.push(food);
  showFoods();  
}
#foods{list-style:none}
<ul id="foods"></ul>
<button type="button" onclick="addFood('Dragonfruit')">Add Dragonfruit</button>
<button type="button" onclick="addFood('Cherry')">Add Cherry</button>
<button type="button" onclick="addFood('Lime')">Add Lime</button>
<button type="button" onclick="addFood('Strawberry')">Add Strawberry</button>

#4


0  

You can use push to add a new element to an array, for example:

可以使用push向数组添加新元素,例如:

foods.push("Kiwi");

#1


0  

I did some modifications of your code for concat and addFruitOnClick function.

我为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();

#2


0  

First, at the end of your script, you should call addToArray(), not addtoArray() (case matters)

首先,在脚本的末尾,应该调用addToArray(),而不是addToArray() (case事项)

Next, the function concat does not update your array in place, you should write

接下来,函数concat不会更新您的数组,您应该编写。

foods = foods.concat([ "dragonfruit", "Cherry" /* ... */ ])

or

[ "dragonfruit", "Cherry" /* ... */ ].forEach(function(fruit){ food.push(fruit) })

Then your code won't run forever anymore.

然后你的代码就不会再运行了。

#3


0  

I slightly changed your code - you can play with the concept to mould it to your needs - basically there is a single array of fruits and this is shown as dynamically created list.

我稍微改变了您的代码——您可以使用这个概念来对您的需求进行建模——基本上有一个单一的水果数组,这是动态创建的列表。

I then have a series of buttons that call a function to add a specific food to the array.

然后,我有一系列按钮,调用一个函数来向数组添加特定的食物。

Clicking an ad button - allows a new fruit to be added to the array and then all you have to do is re-render the lest to show the new content. This could be amended to remove fruits as well:

单击一个广告按钮——允许将一个新水果添加到数组中,然后你所要做的就是重新呈现,以免显示新的内容。这也可以修改,以去除水果:

var foods = ["Banana", "Orange","Apple", "Mango","Lemon"]

showFoods();

function showFoods() {
  var str= '';
  
  foods.forEach(function(food) {
    str += '<li>' + food + '</li>';
   });
   
  document.getElementById('foods').innerHTML = str;
 }

function addFood(food){
  foods.push(food);
  showFoods();  
}
#foods{list-style:none}
<ul id="foods"></ul>
<button type="button" onclick="addFood('Dragonfruit')">Add Dragonfruit</button>
<button type="button" onclick="addFood('Cherry')">Add Cherry</button>
<button type="button" onclick="addFood('Lime')">Add Lime</button>
<button type="button" onclick="addFood('Strawberry')">Add Strawberry</button>

#4


0  

You can use push to add a new element to an array, for example:

可以使用push向数组添加新元素,例如:

foods.push("Kiwi");