Question: In Javascript, you need to fix bug with a loop and closures. Note you need to add a line that actually calls testList(); because there
In Javascript, you need to fix bug with a loop and closures. Note you need to add a line that actually calls testList(); because there is no button like on the site to execute the code.
Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.
|
| function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + list[i]; result.push( function() {alert(item + ' ' + list[i])} ); } return result; } function testList() { var fnlist = buildList([1,2,3]); // using j only to help prevent confusion - could use i for (var j = 0; j < fnlist.length; j++) { fnlist[j](); } } |
|
|
|
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
