I’m doing a simple exercise with an object constructor. in this exercise, I create a form, and every time a user fills the form and clicks the show button, the data will send to an object constructor "Person" and every person’s data will be put into the created object and then every object will be put into "myperson" array and print the array in the console.
but the problem is, the console only shows one index and the other indexes are empty.
document.querySelector(".btn-danger").addEventListener("click",get_data);
let i = 0;
function get_data() {
let myperson = [];
let first_name = document.querySelector(".f_name").value;
let last_name = document.querySelector(".l_name").value;
let age = document.querySelector(".age").value;
myperson[i++] = new Person(first_name, last_name, age);
console.log(myperson);
}
function Person(f_name, l_name, age) {
this.f_name = f_name;
this.l_name = l_name;
this.age = age;
}
<body>
<div class="container">
<form action="" class="mt-5">
<div class="form-group text-right">
<label> firstname </label>
<input type="text" class="form-control f_name" value="">
</div>
<div class="form-group text-right">
<label> lastname </label>
<input type="text" class="form-control l_name" value="">
</div>
<div class="form-group text-right">
<label> age </label>
<input type="text" class="form-control age" value="">
</div>
<button type="button" class="btn btn-lg btn-danger"> show </button>
</form>
</div>
</body>
5
Answers
You should declare you array outside the
get_data
function, in general it should be somewhere globally declared. Now it is created every time get_data is called, hence you always have a new array containing only the last person obj.let i = 0;
so every time when user will click on show button it will override the existing one.instead of setting i=0 first get the count of array and then set i= count+1;
let myperson = [];
due to which older is getting removed from existing array instead you and create a global variable.myPerson should be a global variable, when put myPerson inside the method it will be initialized every time you call the method. Here’s the modified code:
To fix this, you need to declare the
myperson
array outside theget_data
function so that it maintains the previously added person objects. Here’s the modified code:You are deleting the array each time you click the button.
moved the myperson outside the function to keep it.