Bastien Donjon

Développeur web à Bordeaux

Monthly Archive: January 2015

Wednesday

14

January 2015

36

COMMENTS

[Javascript] For in extended Array prototype

Written by , Posted in Javascript

If you have extended Array prototype with functions like this :

1
2
3
Array.prototype.inArray = function(){
    console.log('inArray function');
}

The result of your ‘for’ will contain the properties and new functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
6
7
8
9
for(var i in values){
    if (values.hasOwnProperty(i)) {
        console.log(i + ' : ' + values[i]);
    }
}
 
// =>
// 0 : value1
// 1 : value2

Case 2 with forEach

1
2
3
4
5
6
7
8
function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
values.forEach(logArrayElements);
 
// =>
// 0 : value1
// 1 : value2

Run on JsFiddle