For-loop in javascript: sometimes back to front is better; and one extra trick |
|
Sometimes we need to search and remove several elements in a numerical Javascript Array (so we have to modify array in a loop). First, here are two bad examples of how not to do: 01.// Bad example 1; will produce an exception02.// TypeError: x[i] is undefined03.// on step 404. 05.try {06. x = ['a', 'bb', 'bb', 'c'];07. for (var i = 0, l = x.length; i < l; i++)08. if (x[i].length > 1) x.splice(i, 1);09.} catch (e) {10. //11. window.alert(e);12.}13. 14.// Bad example 2: won't produce an exception15.// but will miss second 'bb'16. 17.x = ['a', 'bb', 'bb','c'];18.for (var i = 0; i < x.length; i++)19. if (x[i].length > 1) x.splice(i, 1);20. 21.// will output wrong result: ["a", "b", "c"]22.console.log(x);And now there are two right ways to do that. Get to know with this theme closely in our programmer's blog: For-loop in javascript: sometimes back to front is better; and one extra trick |
