Reputation: 3
This is my fist question on here, so be nice :D
I am building a basic texting web app and I'm totally stuck. I have a function that creates an object with "name" and "number" values, for a new contact. That object is then pushed into my "contact" array. It all looks like this:
var contacts = [];
$("#add-contact").click(function () {
var newName = $("#new-name").val();
function contactName(name, number) {
this.name = name;
this.number = number;
}
var newNumber = $("#new-number").val();
var newPerson = new contactName(newName, newNumber);
contacts.push(newPerson);
console.log(contacts)
I then should be able to use that information and then enter in a contact name, have a function search my "contacts" array, give me the index and then use the index to call the name and number so I can then send a message and have it all displayed right (not shown). My calling funtion looks like this:
$("#send-button").click(function () {
var userNumber = $("#number-input").val();
var userIndexNumber = contacts.indexOf(userNumber);
appendToConvo(contacts[userIndexNumber]);
});
The "appendToConvo" was just so I could see if I was outputting the right information.
When I ran the first function in Chrome, the console showed that my "contacts" array contained only [contactname]. The function is adding the data for name and number, just not the name of the object to the array, I think. Chrome displays this: Chrome console message This has been driving me crazy for a little bit and I just need some help! Thanks to anyone that can help me!!!
Upvotes: 0
Views: 43
Reputation: 1591
contacts is an array of contactName objects, not an array of numbers, so contacts.indexOf(userNumber)
is returning -1 (indexOf uses strict equality to compare elements against the passed argument, and none of the objects in your array is strictly equal to userNumber
). I suggest you use something like the following to find the contact you are interest in finding:
var matchingContacts = $.grep(contacts, function (c) {
return c.number === user.number;
});
appendToConvo(matchingContacts[0]);
Upvotes: 1