You’re calling $.each(array,fn) or $(selector).each(fn) to iterate over thousands of items in your code, and you suspect that all those function calls may be adding to your load time:
Use a for loop instead of .each(). To iterate over an array, it’s hard to beat this loop:
But there is a catch: this loop works only if your array has no “false” elements, that is,elements whose value is undefined, null, false, 0, or "". Even with that restriction, this loop is useful in many common cases, such as iterating over a jQuery object. Just be sure to cache the object in a variable:
It’s also common to have JSON data that contains an array of objects as in our example from Recipe (Loading Tables Faster):
If you know that none of the objects making up the elements of the names array will ever be null, it’s safe to use the fast loop.
For a more general-purpose loop that works with any array, there is always the classic loop that you’ll see in many places:
But you can improve that loop in three ways:
The result is as follows:
To iterate over an object (not an array), you can use a for..inloop:
$(selector).each(fn) is the customary way to create a jQuery object and iterate over it, but it’s not the only way. The jQuery object is an “array-like” object with .length and, , ..., [length-1] properties. Therefore, you can use any of the looping techniques you would use with any other array. And because the jQuery object never contains “false” elements, you can use the fastest for loop listed at the beginning of the solution.
If you use the time() function from Recipe 5.2 or another profiler to measure loop performance, be sure to test your actual code, not a simplified test case that just runs the loop without the full loop body. The simplified test would miss one potential benefit of the for loop: fewer name lookups resulting from less function nesting. See Recipe 5.13 for the details.
J Query Related Interview Questions
|HTML 4 Interview Questions||HTML Interview Questions|
|HTML 5 Interview Questions||Zend Interview Questions|
|JqueryUI Interview Questions||Dynamic HTML Interview Questions|
|XQuery Interview Questions||jQuery Mobile Interview Questions|
J Query Related Practice Tests
|HTML 4 Practice Tests||HTML Practice Tests|
|HTML 5 Practice Tests||Zend Practice Tests|
|PHP and Jquery Practice Tests||J Query Practice Tests|
|CodeIgniter Practice Tests||Dynamic HTML Practice Tests|
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.