On 19.03.2012 17:23, Krinkle wrote:
<offtopic>
On Mon, Mar 19, 2012 at 9:35 AM, Daniel Friesen lists@nadir-seen-fire.comwrote:
On Mon, 19 Mar 2012 00:40:54 -0700, Dmitriy Sintsovquestpc@rambler.ru wrote: var jqgmap = [];
for ( var mapIndex in jqgmap ) {
This is VERY bad JavaScript coding practice. Please use $.each().
This is rather exaggerated. Even more when looking at that suggestion.
Arrays should, indeed, not be enumerated with a for-in loop. Arrays in JS can only contain numeral indices, so they should simply be iterated with a simple for-loop like this `for (i = 0; i< myArr.length; i += 1) { .. }` (maybe cache length for slight performance gain by reducing property lookups).
My array is numeric but sparse, myArr = []; myArr[0] = a; myArr[1] = b; So I cannot just use incremental key iteration, at least existence of element should be checked.
Using $.each has overhead (+1+n function invocations). When given an array it will do a simple for-loop with a counter. It has overhead of 1+n additional function invocations and context creations. In most cases there is no use for it. There is one case where it is handy and that's when you specifically need a local context for the loop (being careful not to create later-called functions inside the loop, risking all variables being in the post-loop state). If you don't need a local scope for your loop, then using $.each (or the native [].forEach in later browsers) is pointless as it only has overhead of additional function invocations and lowering the position in the scope chain.
When iterating over objects, however, (not arrays) then $.each is no better than a for-in loop because (contrary to what some people think) it is not a shortcut for for-in + if-hasOwn wrapper. When an object is passed, it literally just does a plain for-in loop invoking the callback with the value. jQuery does not support environments where someone extends the native Object.prototype because it is considered harmful (an therefore MediaWiki inherently does not support that either), so a plain for-in loop over an object (excluding array objects) is perfectly fine according to our conventions.
See also http://stackoverflow.com/a/1198447/319266
.... but so much for the good (and bad, evil) parts of javascript :D
I was thinking about Daniel warnings on Array prototyping and thought that proper iteration would check whether the prototype has the same member, then do not include it (skip from) callback. Dmitriy