I have found the following loop annotation in a big project I am working on (pseudocode):
var someOtherArray = [];
for (var i = 0, n = array.length; i < n; i++) {
someOtherArray = modifyObjetFromArray(array[i]);
}
What brought my attention is this extra "n" variable. I have never seen a for lop written in this way before.
Obviously in this scenario there is no reason why this code couldn't be written in the following way (which I'm very much used to):
var someOtherArray = [];
for (var i = 0; i < array.length; i++) {
someOtherArray = modifyObjetFromArray(array[i]);
}
But it got me thinking.
Is there a scenario when writing such a for loop would make sense? The idea comes to mind that "array" length may change during the for loop execution, but we don't want to loop further than the original size, but I can't imagine such a scenario.
Shrinking the array inside the loop does not make much sense either, because we are likely to get OutOfBoxException.
Is there a known design pattern where this annotation is useful?
Aucun commentaire:
Enregistrer un commentaire