$.each([collection]) vs $([collection]).each()

前端 未结 2 1341
生来不讨喜
生来不讨喜 2021-02-14 09:54

Both methods appear to produce the same results, but I\'ve been hard-pressed to actually convince people that the second method works, since it\'s apparently not commonly known.

相关标签:
2条回答
  • 2021-02-14 10:33

    I'm not sure what everybody else says...but I almost exclusively use your second method there.

    Coming from .NET land...it just makes more sense to me and makes things easier to read.

    0 讨论(0)
  • 2021-02-14 10:41

    The difference between the two is actually exponential depending on how you are using it.

    The first $.each constitutes a single function call to start the iterator.

    The second $(foo.vals).each makes three function calls to start the iterator. The first is to the $() which produces a new jQuery wrapper set (Not sure how many other function calls are made during this process). Then the call to $().each. And finally it makes the internal call to jQuery.each to start the iterator.

    In your example, the difference would be negligible to say the least. However, in a nested use scenario, you might find performance becoming an issue.

    Finally, Cody Lindley in jQuery Enlightenment does not recommend using $.each for iterations greater than 1000 because of the function calls involved. Use a normal for( var i = 0... loop.

    0 讨论(0)
提交回复
热议问题