Home > Blockchain >  How to remove elements from array
How to remove elements from array

Time:05-24

Thanks for viewing. I have a program that can create a list of user inputs. The program can add people & remove people (starting from the top). This program also limits inputs to 7.

When the limit is reached, the oldest input in the array gets erased, and then the new input is going to appear. Basically:

a b c d e f g 

(a is the oldest, and the g is the newest)

Becomes:

b c d e f g h

However, even if the program can already add elements in the array, what I can't understand is that although my program has the pop()function to remove people, I still can't remove anyone from my list. Furthermore, the input limitations is not followed.

Is there a missing part in my code that does the problem? Thanks.

var people = [7];

function myFunction() {
  var x = document.getElementById("list");
  people.push(document.getElementById("input").value);
  x.innerHTML = people.join('<br/>');
}

function myFunctions() {
  var x = document.getElementById("list");
  people.pop();
  console.log(people);
}
<!DOCTYPE html>
<html>

<body>
  <form>
    <input id="input" type=text>
    <input type=button onclick="myFunction()" value="Add" />
    <input type=button onclick="myFunctions()" value="Remove" />
  </form>

  <div id="list">
  </div>
</body>

CodePudding user response:

Please, check if it was you want?

It seems you expect that vanilla javascript variables be reactive as in vue js or react js but they don't.

 <!DOCTYPE html>
    <html>
    
<style>
</style>
      <script>
       var people = [7];
    
        function myFunction()
        {
          if(people.length === 7) // you should check the array size
            return console.log("it can't  add more people!");

          var x = document.getElementById("list");
          people.push(document.getElementById("input").value);
          x.innerHTML = people.join('<br/>'); 
        }
        function myFunctions()
        {
          var x = document.getElementById("list");
          people.pop(); 
          x.innerHTML = people.join('<br/>'); // you should update the list
          console.log(people);
        }
      </script>
<body>
     <form>
      <input id="input" type=text>
       <input type=button onclick="myFunction()" value="Add"/>
       <input type=button onclick="myFunctions()" value="Remove"/>
      </form>
    
     <div id="list"> 
      </div>
    </body>

CodePudding user response:

I'm not sure if you remember the definition of index, but an array list of 7 is supposed to be [6], as the corresponding index to every variable in the list starts with 0 instead of 1.

Try to update your list before you go straight to console.log!

  • Related