0

I wrote some JavaScript on Chrome and then tried to run it in IE8. The first thing I ran into was the lack of Array.map, Array.filter and all their useful cousins. To get around this, I added some of the shims found here.

This broke all my for ... in ... loops, like this:

>> c = [1];
{...}
>> for(i in c) { console.log(i);}
LOG: 1
LOG: indexOf
LOG: lastIndexOf
LOG: filter

I would want that to iterate over array entries only. Is there a way around this or do I need to go back to writing for(i=0;i<c.length;++i) loops?

Community
  • 1
  • 1
themel
  • 8,825
  • 2
  • 32
  • 31

1 Answers1

2

You need to sanitize your loops, using hasOwnProperty the shim adds functionality to the array prototype and you end up looping over the added functions.

for(i in c){
    if(c.hasOwnProperty(i))
    {
        console.log(i);
    }
}

References: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

http://msdn.microsoft.com/en-us/library/328kyd6z(v=vs.94).aspx

Crockford on for .. in http://javascript.crockford.com/code.html search for "hasOwnProperty"

Kristoffer Sall-Storgaard
  • 10,576
  • 5
  • 36
  • 46
  • I'm I the only one who thinks the `hasOwnProperty` "pattern" (is something a pattern if it's unavoidable?) is one the ugliest in JS? Also, I believe Crockford said "They added `hasOwnProperty` precisely for this reason. They just forgot to tell anyone about it" :) – Flambino Aug 19 '11 at 08:15
  • I wouldnt call it a pattern, I'd call it a necessity. The only way to avoid it is `:d3w`not to play avoid polluting the namespace. Edit: – Kristoffer Sall-Storgaard Aug 19 '11 at 08:24
  • Yeah, necessity is a better word than "pattern" (even with the quotes). Even if you're diligent about keeping the namespace clean, that `if hasOwn…` should always be there. But really, there should just be a simpler/prettier (and built-in) way of looping just the immediate properties of an object… it just irks me whenever I see that `for…in…if` construction – Flambino Aug 19 '11 at 08:38
  • I just wish people would aknowledge that builtins are not theirs to play with... if you want a specialized array, make you own (concept: http://jsfiddle.net/wrSZc/) – Kristoffer Sall-Storgaard Aug 19 '11 at 09:04
  • That is indeed the way to go. But as long as javascript is… well, javascript, host objects _are_ for people to play with. Doesn't mean they should, but since anyone can, someone will. I wish there was a better way to handle it though, because extending host objects often makes for nice (-looking) code. If only it didn't have the nasty consequences… – Flambino Aug 19 '11 at 09:21