Adding new elements to an array

时间:2017-04-10 01:31:33

标签: javascript html

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?

  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.

  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.

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.

4 个答案:

答案 0 :(得分:0)

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

foods.push("Kiwi");

答案 1 :(得分:0)

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

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)

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>

答案 3 :(得分:0)

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

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

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

or

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

Then your code won't run forever anymore.