0

A few people I work with include on their sites some javascript I wrote and host. But some of those sites use prototype.js or some other framework and its causing some big problems.

For example:

var test = {"one":[{"a":"b"}]};
for (var i in test.one) { console.log(i); }

The expected result of this would be "0" in the console (i being the key to that array)

But if I go to a site like prototypejs.org and run the same code in firebug's console, I get a list of all the prototype junk (each, eachSlice, etc..)

Try running it in your console here on stackoverflow, it returns "0" as expected.

How do I prevent this? Any good workarounds?

Rob W
  • 341,306
  • 83
  • 791
  • 678
nolanpro
  • 2,257
  • 3
  • 23
  • 23

3 Answers3

4

Either test that each property you enumerate is NOT in the prototype

for (var i in test.one) { 
   if (test.one.hasOwnProperty(i)) {
      console.log(i); 
   }
}

or don't enumerate arrays.

for (var i = 0, ii = test.one.length; i < ii; i++) {
     console.log(i);
}

Any code that extends Object.prototype is not your problem. You should not have to guard against that.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • Thanks! I think I have to use hasOwnProperty() instead of for(i...i++) because i'm dealing with string keys (aka object properties, aka associative array keys) where there's no such property 'length'. – nolanpro May 14 '11 at 08:32
0

You can learn to work nicely with others, by not using a for in loop without checking for hasOwnProperty on each iteration, or you can explode all their code at the start of yours:

for(var p in Array.prototype)delete Array.prototype[p];

It will only destroy non-native properties.

Do the same for Object and anything else you want neutered.

kennebec
  • 102,654
  • 32
  • 106
  • 127
0

Prototype.js stuffs Array.prototype with additional methods.

Here's an excerpt from prototype.js:

  Object.extend(arrayProto, {
    _each:     _each,
    clear:     clear,
    first:     first,
    last:      last,
    compact:   compact,
    flatten:   flatten,
    without:   without,
    reverse:   reverse,
    uniq:      uniq,
    intersect: intersect,
    clone:     clone,
    toArray:   clone,
    size:      size,
    inspect:   inspect
  });

You can find all these properties in the output of your first for..in loop.

Can be prevented by not iterating over arrays with for..in and instead using var i; for (i = 0; i < arr.length; i++)

Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34