3

Assuming element with id 'id2' is a textarea with the following entries:

[email protected], [email protected], [email protected]

When I run this, I am getting values 0, 1 and 2 - why?

jQuery('#myid').submit(function() {
    var temp = jQuery('#id2').serializeArray();
    var email_arr = temp[0].value.split(',');
    for (e in email_arr)
        alert(e);
  return false;
});
1
  • Try alert(temp)ing, and see what you get :) Commented Jun 23, 2011 at 22:55

3 Answers 3

3

Because for ... in iterates keys, not values, so use alert(email_arr[e]) instead.

Sign up to request clarification or add additional context in comments.

Comments

2

Because e contains the key of the object. To get the value, use email_arr[e].

Really, it's not wise to use for...in to iterate Arrays because it iterates, not just the items in the collection, but all the members of the Array including custom properties and methods. So, as soon as someone extends Array, you will get unexpected results in your for...in loop. For example, if you are using IE7 and you want to use Array.forEach() you'll have to extend Array as recommended by MDC. With Array extended, now each Array you create will have an extra property that will show up as you iterate using for...in.

Instead, use Array.forEach(). It's solves all kinds of problems that can crop up when looping through Arrays. This does what you are trying to do:

email_arr.forEach(function(email, index, list)
{
    alert(email);
});

Comments

0

Unfortunately, in javascript, for ... in ... loop are not working the same way as in python. Your e variable is actually looping on the "index" (keys) of your array.

You should get the desired result by looking at email_arr[e].

2 Comments

I wouldn't say that it is unfortunate, it's a simple way to get both the key and the value within the loop.
well. I would. :D That's counterintuitive, because it does not match natural language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.