Why does my array length always come out to 0 even though var email is equal to a string. (I’ve alerted out var email and the data is there).
var emails = new Array();
//get all the emails
$('.emailBox input').each(function (i)
{
var email = $(this).val();
if(email != '')
{
emails[email] = email;
alert(emails.length);
}
});
Because you’re adding a property to the array.
Instead try
emails.push(email);This is the same as
emails[emails.length] = emailAs an aside:
var emails = new Array();Is bad. You should be using
[]instead ofnew Array()mainly because it’s more terse and readable.if (email != '') {The above can be replace with
if (email) {in case jQuery ever returnsundefinedornullTo make the entire code more elegant you should use
Or without jQuery
Although you’ll need a QSA shim and a ES5 shim for legacy platform support.
Edit:
If you want the array to be unique then reduce it.