Safe Array Iteration in Gyroscope December 18, 2013

View all articles from Gyroscope Development Blog

We found out that the following code in Safari produces different results than other browsers. To see the matter yourself, create a test file under the Gyroscope folder, where tabs.js is located.

<html>
<body>
<div id="res"></div>


<script src="tabs.js"></script>
<script>
objs=['x', 'y', 'z'];
for (key in objs){
    document.getElementById('res').innerHTML+=objs[key]+' ';
}
</script>
</body>
</html>


In Firefox, IE and Chrome, the results are expected:

0 1 2



Safari, on the other hand, mixes in the prototype function names:

0 1 2 push pop



The corrupted array could break certain functions. The cause of the issue is that the Array class is extended in tabs.js with two prototype methods: push and pop. Although most browsers support these two methods, and that modifying prototypes of builtin objects could cause averse side effects (as in this case), we deemed the extension necessary, as the push and pop functions are inconsistently implemented in many browsers.

To fix the function artifacts in the array, we simply check the type of the array element. This works well if elements in the array are not functions:

for (key in objs){
    if (typeof(objs[key])=='function') continue;
    document.getElementById('res').innerHTML+=objs[key];
}



It's worth noting that the only other browser we found that also displayed such behavior is Internet Explorer 5.0. Interesting, to say the least.

Our Services

Targeted Crawlers

Crawlers for content extraction, restoration and competitive intelligence gathering.

Learn More

Gyroscope™ ERP Solutions

Fully integrated enterprise solutions for rapid and steady growth.

Learn More

E-Commerce

Self-updating websites with product catalog and payment processing.

Learn More