Strange key names in for-in-loops
How to handle prototype manipulation problems
Perhaps you already happened to notice that going through the properties of an object or the elements of a (pseudo) associative array using the for-in-loop lets the script find strange keynames which you didn't expect to be part of your object. Those, most probably, are the names of prototypes which have been defined somewhere in this way:
Object.prototype.myFnc = function() { // [...] } // Or: Array.prototype.myFnc = function(){ // [...] }
This can be very annoying, and it's not a convenient solution to check in each for-in-loop if the found key name is identical to one of the strange names in order to pay attention to it or not. But if you use the the free Turboid framework or copy the code at the end of this article you get a quite convenient solution which allows you to use for-in-loops almost as usually, without building in intricate filter queries.
So, instead of:
for(var key in myObj){ // Do something }
You write:
for(var key in myObj){ if(keyOk(key)){ // Do something }}
If you'd like to save some letters you can also write:
from(myObj, function(key){ // Do something });
However, if you want to build one loop into another, the from()-method is not the first option.
Try out the solutions mentioned above after copying the following code or downloading the Turboid framework:
function keyOk(key){ if(!(key in Object.prototype) && !(key in Array.prototype) && key!="undefined") return 1; else return 0; } function from(list, fnc){ for(var k in list){ if(keyOk(k)){ fnc(k); }} };Enjoy!
Comments
Add comment: