I'm creating a small program where I have a page with two input fields and a user can enter their name and the number of calories they've eaten today. After a person enters their data, I want to display it alongside other people's data in a list sorted by total calories.
I also want that person to be able to re-enter their name and additional calories and have it update their total calories (as opposed to creating another entry with their name and most recent calorie amount).
I am assigning the input values to variables, using those to create a new Person object, then pushing that object to an array.
How can I test to see if the array contains a Person object with a name that already exists? My test isn't recognizing names that have already been submitted. If a person's name has already been entered, I'd like to update their total calories instead of creating a new Person object.
My javascript code:
(function () {
"use strict";
/* Person object constructor */
function Person(name, calories) {
this.name = name;
this.calories = calories;
}
function addToList() {
var name = document.getElementById('name').value;
var calories = document.getElementById('calories').value;
/*
Check to see if list already contains person's name
If yes, update their calorie amount.
If not, create a new player and add them to the list.
*/
for (var i = 0; i < list.length; i++) {
if (list[i] === name) {
alert('This person already exists.');
} else {
var newPerson = new Person(name, calories);
list.push(newPerson);
}
}
}
var list = [];
$('#add').click(addToList);
})();