Last modified: 2011-05-12 19:16:09 UTC
Created attachment 8528 [details] This patch reverts for-in loops back to basic style. The Semantic Forms extension uses "for ... in" loops for iterating through the indexes of an array. But "for ... in" actually iterates through the property names of an object. If the array has additional properties (e.g. from PrototypeJS) like a.name = 'MyArray'; the JS can break with "for ... in" loops. More information could be found at http://proto-scripty.wikidot.com/prototype:tip-looping-through-arrays. Therefore i recommend to revert "for ... in" loops back to the basic vanilla "for (;;)" style. I attach a patch that applies these changes to /libs/SemanticForms.js
Alright, that seemed like a reasonable suggestion, so I made those changes in SVN. Thanks for the patch. I assume this is for use by SMW+ - out of curiosity, are you planning to switch from Prototype to jQuery at any point, or are you staying with Prototype?
Note, you don't necessarily have to not use for..in loops, you just need to use the hasOwnProperty method of Object to check. (see http://javascript.crockford.com/code.html#for%20statement )
Thank you applying the patch. Yes, the issue arised from the use of the PrototypeJS lib (in SMW+). I don't know the current effort on transform all prototype scripts to jQuery but i'm going to ask our dev team about it. All i can say is that upcoming scripts are mostly implemented in jQuery now. @Bawolff: Yes, this recommendation would cover most cases since it skips prototype members of the object (e.g. added by libraries). But the following code would still not work as expected: var a, index; a = ['a', 'b', 'c']; a.name = 'MyArray'; for (index in a) // <= WRONG { if (a.hasOwnProperty(index)) { alert(index + ' = ' + a[index]); } }
(In reply to comment #3) > > @Bawolff: > Yes, this recommendation would cover most cases since it skips prototype > members of the object (e.g. added by libraries). But the following code would > still not work as expected: > > var a, index; > a = ['a', 'b', 'c']; > a.name = 'MyArray'; > for (index in a) // <= WRONG > { > if (a.hasOwnProperty(index)) { > alert(index + ' = ' + a[index]); > } > } Well I suppose that varies with your definition of "expected". It would behave how I expect it would, as well as exactly the same as how such constructs behave in other languages like PHP. A basic for loop is probably always better when you just want to go through the numeric keys in order.