[Javascript] For in extended Array prototype
Written by Bastien Donjon, Posted in Javascript
If you have extended Array prototype with functions like this :
Array.prototype.inArray = function(){ console.log('inArray function'); }
The result of your ‘for’ will contain the properties and new functions.
var values = ['value1', 'value2']; console.log(testArray); // => ["value1", "value2", inArray: function] for(var i in values){ console.log(i + ' : ' + values[i]); } // => // 0 : value1 // 1 : value2 // inArray : function (){ // console.log('inArray function'); // }
To fix this issue :
Case 1 with hasOwnProperty
for(var i in values){ if (values.hasOwnProperty(i)) { console.log(i + ' : ' + values[i]); } } // => // 0 : value1 // 1 : value2
Case 2 with forEach
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } values.forEach(logArrayElements); // => // 0 : value1 // 1 : value2
Run on JsFiddle