Question

Please provide correct answer as well as notes to how it was reached. This one is...

Please provide correct answer as well as notes to how it was reached.

This one is a real gotcha for many people, so you need to understand it. 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.

The line result.push( function() {alert(item + ' ' + list[i])} adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:

1

2

pointer = function() {alert(item + ' ' + list[i])};

result.push(pointer);

Note that when you run the example, "item3 undefined" is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the currentvalue for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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]();

    }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// this function is used to create a list of pushed functions
function buildList(list) {
var result = []; // create an empty array
// for each element in the list
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
// push a function with an alert message
//The line result.push( function() {alert(item + ' ' + list[i])} add
// a reference to an anonymous function three times to the result
// array. If you are not so familiar with anonymous functions think
//of it like:
// 1. pointer = function() {alert(item + ' ' + list[i])}; => an anonymous function
// 2. result.push(pointer); => poiter to an anonymous function pushed to result array
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}


// This function is used to test the functionality of pushing a function to an array
function testList() {
// first create a list of three numbers
var fnlist = buildList([1,2,3]);
// using j only to help prevent confusion - could use i
// call the pushed function for each number in the list
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}

/*
Note that when you run the example, "item3 undefined" is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the currentvalue for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').
*/

Note: I did not find any question in this post. Hence, I have provided the description of this code snippet.

Add a comment
Know the answer?
Add Answer to:
Please provide correct answer as well as notes to how it was reached. This one is...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a...

    C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a structure called MyToDo to hold information about each todo item. The members of the MyToDo struct are description, due date, and priority. Each of these items will be stored in an array called ToDoList. The definition for the MyToDo struct should be placed in the header file called ToDo.h Visually think of the ToDoList like this: There are two ways to add items to...

  • Please answer python questions? class ItemPack ): 21 def-init--(self): self.--storage=[] self. _.jump -1 self. _.mid-self. ..jump...

    Please answer python questions? class ItemPack ): 21 def-init--(self): self.--storage=[] self. _.jump -1 self. _.mid-self. ..jump def __iter.(self) self._.mid-int (len (self..storage)-1)/2.0) self. _.jump 0 return (self def __next..(self): 10 ind self .-_aid+self.--jump if ind<0 or ind >=len (self.--storage): 12 13 14 15 raise StopIteration O vToRet self.--storage [ind] if self.--jump <=0 : self.--Jump 1-self.--Jump - else return (vToRet) self..storage.append (item) return (len(self.--storage)=#0) 17 self.--jump*=-1 19 20def stuff (self, item) 21 22def isEmpty (self) 24def unpack (self): if len (self. .storage)0return...

  • HELLO, PLEASE TAKE TIME TO ANSWER THIS QUESTION. PLESE ENSURE ITS CORRECT AND SHOW THAT THE...

    HELLO, PLEASE TAKE TIME TO ANSWER THIS QUESTION. PLESE ENSURE ITS CORRECT AND SHOW THAT THE PROGRAM RUNS. Task 1: Enforcing const-ness throughout Your first job will be to go through all of the code and decide which functions should be declared const. You should find several places throughout the program where this makes sense. We will also make the id data member in the Customer class const , as once a customer has been created their ID will never...

  • I need this in C++. This is all one question Program 2: Linked List Class For...

    I need this in C++. This is all one question Program 2: Linked List Class For this problem, let us take the linked list we wrote in a functional manner in a previous assignment and convert it into a Linked List class. For extra practice with pointers we'll expand its functionality and make it a doubly linked list with the ability to traverse in both directions. Since the list is doubly linked, each node will have the following structure: struct...

  • Need this in C The starter code is long, if you know how to do it...

    Need this in C The starter code is long, if you know how to do it in other way please do. Do the best you can please. Here's the starter code: // ----------------------------------------------------------------------- // monsterdb.c // ----------------------------------------------------------------------- #include #include #include // ----------------------------------------------------------------------- // Some defines #define NAME_MAX 64 #define BUFFER_MAX 256 // ----------------------------------------------------------------------- // Structs typedef struct { char name[NAME_MAX]; int hp; int attackPower; int armor; } Character; typedef struct { int size; Character *list; } CharacterContainer; // ----------------------------------------------------------------------- //...

  • Questin 1 (CO 2) Which of the following is not a valid name in python? last_name...

    Questin 1 (CO 2) Which of the following is not a valid name in python? last_name lastName last name lname Question 2 (CO 3) How many times will “Hello World” be displayed after the following code executes? num=2 while num<12:     print("Hello world")     num+=2 2 12 5 4 Question 3 (CO 1) The following code contains an error, what type of error is it and what line number is it? 1 count=1 2 while count<4 3    print("count = ",...

  • Hello I need help with this program. Should programmed in C! Program 2: Sorting with Pointers...

    Hello I need help with this program. Should programmed in C! Program 2: Sorting with Pointers Sometimes we're given an array of data that we need to be able to view in sorted order while leaving the original order unchanged. In such cases we could sort the data set, but then we would lose the information contained in the original order. We need a better solution. One solution might be to create a duplicate of the data set, perhaps make...

  • Help needed with Python 3: Dictionaries and Sets. The problem is one that asks the user to create...

    Help needed with Python 3: Dictionaries and Sets. The problem is one that asks the user to create a completed program that prompts the user for the name of a data file, and reads the contents of that data file, then creates variables in a form suitable for computing the answer to some questions. The format should be in the same manner as the attached .py file. All subsequent assignment details (.py and .csv files) can be found at this...

  • Question 1 An array is NOT: A - Made up of different data types. B - Subscripted by integers. C -...

    Question 1 An array is NOT: A - Made up of different data types. B - Subscripted by integers. C - A consecutive group of memory chunks. D - None of the choices. Question 2 How many times is the body of the loop executed? int i=1; while(true) { cout << i; if(++i==5) break; } A - Forever B - 4 C - 5 D - 6 E - 0 Question 3 What is wrong with the following piece of...

  • Please help with my car traffic simulator! Code that I already have below, I do not know how to...

    Please help with my car traffic simulator! Code that I already have below, I do not know how to start it off! public class IntersectionSimulation { private final static int EAST_WEST_GREEN_TIME = 30 ; private final static int[] NORTH_SOUTH_GREEN_TIMES = { 20, 24, 30, 42 } ; private final static int[] CAR_INTERSECTION_RATES = { 3, 5, 10 } ; private final static int[] CAR_QUEUEING_RATES = { 5, 10, 30 } ; private final static int[] EXPERIMENT_DURATIONS = { 3*60, 5*60,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT