[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
tEcr5zqJ3BR
Yhx0iyIU3fx
0Yqd1d9InRG
WoPDmjPrJXD
oI2MkrqSZUy
r60ZqmSRG3X
6bl3xp0efBA
G23PwkPqBr6
tBQBmxRQv9G
DoV6T9TG587
YfDmbmihd2G
GPXM4YKcktl
iz1ENDWgx8O
wqNOX89saeg
Wv6v6LEJD2Z
s8ipLioByRv
yO2LLE3ssjK
OH8wxULVbut
49bFuLAG3qq
0fvtGWNyeMS
f5aLRYbv5eb
10vSbLrrSOi
MAwI7FRDuaw
JuVR1KobHih
RYEeMxuDWV8
yOrLPiz6ngb
2zQEZcsJlBz
XWruTaeAuSk
JSeCnVDj1zH
AyErWSpmGpY
cQVg1K6zWjg
FLWrFrblVCc
yUceM0v1o9h
o8m2EyF5qby
8EUCWiaXJqt
BR7VJcNvP0l
Categories
Recent Posts
Mes sites
Archives