Avoiding the use of the for…in loop over an array

When tailoring Service Manager, you often need to iterate over an array. However, using a for…in loop to iterate over an array may return unexpected results, particularly, in the two scenarios illustrated below. We recommend that you use the for ([initialization]; [condition]; [final-expression]) loop instead when iterating over an array object.

Enhancing an array object with custom methods

Service Manager currently uses a JavaScript Engine that complies with JavaScript 1.5, in which some Array.prototype functions are implemented as built-in functions. When enhancing an array object with a custom method, the for...in loop iterates on all items in the array including the custom method. Similar issue also occurs to customized Array.prototype functions, as demonstrated in the following example code and its output. This behavior might lead to errors that are difficult to debug.

Array.prototype._prototypeFunction = function() { 
// prototype function will be iterated as non built-in property
            print('prototype element');
}
print(‘built-in  property: ‘ + array.length); 
// length is built-in property of array object, it will not be iterated within for…in statement
for(var item in [1]) {
      print(‘ non built-in  properties of Array type:’ + item); 
      //iterate the non built-in properties
}

Output:

non built-in  property of Array type: _prototypeFunction 
// prototype function added as non built-in
non built-in  property of Array type: 0
built-in  property: 4

In this situation, you can use a guarding if statement to help debug the code. For example:

if (<array> .hasOwnProperty(<item index>))

or

if (typeof(<array>[<item index>]!="function")

Iterating out of order

The for…in loop iterates objects in an order according to the ASCII values of the property names. Do not use the for…in loop to iterate over an array when the index order is important. See the following example code and its output.

var array = [1,2,3];
array[‘_’] = ‘test’;
// interrupting element
array[10] = 10;
for(var item in array) {
      print(‘ non built-in  properties of Array type:’ + item); 
      //iterate the non built-in properties
}

Output:

non built-in  property of Array type : 10
// Missing index 3~9!
non built-in  property of Array type: _
//interrupt the element index order
non built-in  property of Array type: 2
non built-in  property of Array type: 1
non built-in  property of Array type: 0      

For more information about using the for...in statement, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in.