最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterate over two arrays using jQuery.each()? - Stack Overflow

programmeradmin2浏览0评论

How can I iterate two arrays through a single call to jQuery .each()?

Something like this clearly won't work:

$.each(arr1, arr2, function(i,v){
  //do something...
});

So how can this be done?

How can I iterate two arrays through a single call to jQuery .each()?

Something like this clearly won't work:

$.each(arr1, arr2, function(i,v){
  //do something...
});

So how can this be done?

Share Improve this question edited Aug 5, 2012 at 14:31 Peter-Paul van Gemerden 7,01132 silver badges37 bronze badges asked Aug 5, 2012 at 14:16 SamSam 1,1453 gold badges14 silver badges24 bronze badges 8
  • The docs show very clearly that you can't do that, and running the code will show very clearly that you can't do that. – user1106925 Commented Aug 5, 2012 at 14:20
  • @amnotiam why did you down vote the question? did you see the Jon's answer? – Sam Commented Aug 5, 2012 at 14:23
  • 2 Because your question shows no basic research effort. Hover your mouse pointer over the down-arrow, and read the popup. – user1106925 Commented Aug 5, 2012 at 14:24
  • ...tell you what, I'll edit your question into what you're actually asking. – user1106925 Commented Aug 5, 2012 at 14:27
  • Sam - Is your intention to iterate through the values of arr1 first, and then the values of arr2? Or do you want to iterate through both in parallel to process the first element from both arrays at once, then the second element from both, etc.? – nnnnnn Commented Aug 5, 2012 at 14:27
 |  Show 3 more comments

2 Answers 2

Reset to default 11

An alternative to .concat would be double $.each:

$.each([arr1, arr2], function() {
    $.each(this, function(i, v) {
        // do something
    });
});

This could turn out being faster if the arrays contain lots of items.

@PPvG this is the code I though, I got two arrays that contains few words each, and using $.each() I wanted to append them in <p> tag arr1 and arr2. content of arr1 first arr2 secondo it's no matter sequence. – Sam 4 secs ago

You could .concat them for the iteration:

$.each(arr1.concat(arr2), function(i,v){
  //do something...
});

Demo: http://jsfiddle.net/ZG4wq/2/

发布评论

评论列表(0)

  1. 暂无评论