Search code examples
javascriptarraysbuttonreset

How to clear the contents of an Array in javascript by clicking a button?


I have a number of buttons that when clicked add a word to an array. This array is used in the url name to download a file:

 <button id="button9" onclick="myFunction7();"</button>

 <script>
 var a = []; 
 function myFunction7() { 
 a.push("h"); 
 }

 <button id="button10" onclick="myFunction8();"</button>

 <script>
 var b = []; 
 function myFunction8() { 
 b.push("h"); 
 } 


 var url = [a,b,c,d];

(I have just included two buttons, they also exist for c, d in same format)

The function for the buttons works and correct file is loaded. Is there a way to reset the url variable and empty the array? I would like to have a button that resets the url variable on my webpage so a new array can be created. I have created a button that refreshes the entire page but this is not ideal as each time my web page has to re load just to clear the array!


Solution

  • To clear an array you only need to re-declare it as an empty array url = []

    var url = ['a', 'b', 'c', 'd'];
    console.log(url) // added for example
    
    function clearArray() {
      return url = []
    }
    function getArray() {
      return console.log(url)
    }
    <button onclick="clearArray(); alert('Array cleared. Now click getArray() button')">Clear Array</button>
    <button onclick="getArray()">Get Array</button> <!-- click me after clearing the array -->