dailymotion/vast-client-js — pull request #15 by rhumlover (2013-11-07 19:50:43+00:00)
Title: Traverse ad responses backwards

When we loop through an array on which we perform a splice operation in order to remove an element, the splice method re-indexes the array, so our original `for` loop based on array length will be wrong, and will loop through several undefined objects at the end:

```
var ar = ['ok', 'ok', 'ok', 'nope', 'ok', 'nope', 'ok', 'nope'],
len = ar.length,
i = 0,
item;

for (i; i < len; i++)
{
item = ar[i];
if (item === 'nope')
{
ar.splice(i, 1);
}
console.log (i + ':' + item);
}

output:

0:ok
1:ok
2:ok
3:nope
4:nope
5:nope
6:undefined
7:undefined
```

We should loop the array backwards, then reindexing array won't have any effect because the next elements we'll parse will be before the previous removed element, so we'll only parse the first remaining objects:

```
var ar = ['ok', 'ok', 'ok', 'nope', 'ok', 'nope', 'ok', 'nope'],
len = ar.length,
i = 0,
item;

while (len--)
{
item = ar[len];
if (item === 'nope')
{
ar.splice(len, 1);
}
console.log (len + ':' + item);
}

output:

7:nope
6:ok
5:nope
4:ok
3:nope
2:ok
1:ok
0:ok
```