开发者

whats wrong with this simple snippet (parsing string into array)?

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

a@123.com, b@123.com, c@123.com开发者_运维技巧

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;
});


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


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);
});


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].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜