开发者

jQuery.map() and iteration

开发者 https://www.devze.com 2023-01-22 08:40 出处:网络
I\'m working my way through the O\'Reilly jQuery Cookbook. On p.65 there is an example that looks wrong to me, but I\'m new to jQuery (less than a week) so I figure it is very likely that I am the one

I'm working my way through the O'Reilly jQuery Cookbook. On p.65 there is an example that looks wrong to me, but I'm new to jQuery (less than a week) so I figure it is very likely that I am the one who is confused.

The code intends to get the first three items from an ordered list & do something with them; for simplicity's sake (on the book's part) in the selector, there is only one list on the page.

They give the following code (I've simplified slightly, but not in the relevant portion); the outer two layers are, of course, boilerplate (a closure so that $ will work as desired, and code to make this fire when the page loads).

(function($){
    $(document).ready(function(){
        var arr = $.map($('li'), function(item, index){
            while (index < 3)
            {
     开发者_Python百科            return $(item).html();
            }
            return null;
        });
        /* do something with the resulting array; 
           I've deliberately simplified from the book here */
        alert(arr.join(",");
    });
})(jQuery);

The explicit iteration (while) doesn't make sense to me. As I understand it, the inner anonymous function should be called once for each element of the array, so I would expect an if, not a while.


This loop will never be executed more than once. It is functionally equivalent to if and I'm sure that's what the author meant to write.

There's an unconfirmed errata list on the O'Reilly website.


Yes, you're correct in your understanding. It's a bad example.


That code should have an if there, a while only exists because of the return, which is a bit of an abuse of while in this case, IMO.

As an illustration with :lt(), you can shorten that whole example down to:

(function($){
  $(function(){
    var arr = $('li:lt(3)').map(function(){
      return $(this).html();
    }).get();
    alert(arr.join(",");
  });
})(jQuery);
0

精彩评论

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