Creating a large array of functions can be done by defining each function within the array individually, ensuring proper

I attempted to define an array of functions using the code below, but encountered issues with retrieving the value of 'i' outside of the loop.

<script>
var f = []
for (var i=0; i<1000; i++){
    f[i] = function(){
        return i
    }
}
console.log(f[3]);
</script>

Instead of resorting to a brute-force method of writing 1000 lines of code to define the functions, I am curious if there are alternative approaches to tackle this problem. I faced a similar issue in Java, which is discussed in this Stack Overflow post about Array of function pointers in Java. Any insights in either Java or JS would be greatly appreciated.

Answer №1

To ensure each function instance has its own variable, you can encapsulate it inside an immediately executed function within the loop:

var funcArray = [];
for (var index = 0; index < 1000; index++){
  (function(index){
    funcArray[index] = function(){
      return index;
    }
  })(index);
}
console.log(funcArray[3]());

See it in action: http://jsfiddle.net/Guffa/rPKss/

Answer №2

Dealing with a closure/scope problem requires locking in the value of a variable

<script>
var arr = [];
for (var x=0; x<1000; x++){
    (function(y) {
        arr[y] = function(){
            return y;
        }
    })(x); // By passing as argument to IIFE, we limit the scope
}
console.log(arr[5]);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable t ...

Comprehending the intricacies of routing within AngularJS

Question: I've been looking into this issue, but there seems to be conflicting answers. I created a simple example in Plunker to understand how routers work in AngularJS, but I'm having trouble getting it to function properly... Below is my inde ...

Issue with triggering blur event in Internet Explorer while using Angular 2+

The issue discussed in the Blur not working - Angular 2 thread is relevant here. I have a custom select shared component and I am attempting to implement a blur event to close it when the component loses focus. // HTML <div (blur)="closeDropDown()" t ...

Refreshing the page using AJAX in WooCommerce after executing my custom script

I am experiencing an issue with WooCommerce. I am trying to incorporate a custom jQuery script that executes after clicking the add to cart button. When I do not include my script, everything functions properly - the AJAX request triggers and the product i ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

What is the process for packaging my JavaScript application?

Based on my research, I'm curious to know what is the most effective method for distributing a Javascript application. Is it considered best practice to distribute applications using npm packages? Or is npm primarily used for distributing frameworks? ...

Is there a way to prevent an iframe from being recorded in Chrome's browsing history?

I'm in the process of developing a Chrome extension that inserts an Angular application into the user's browser window to create an interactive sidebar. I've been successful in most of my goals by inserting an iframe through a content script ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

Challenges in using Three.js on mobile devices with orientation capabilities

I'm currently running tests on a web application built using three.js, and it seems that users on tablets, especially Android devices, are experiencing some unusual behavior within the scene. https://i.sstatic.net/FkFi3.jpg Below is how the view sho ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

Optimal data structure for my array/collection

Is there a recommended method to store an enum value and a number in a collection or array while also being able to update a specific value efficiently? Performance impact considerations are important. For example: enum Colour {Red, Yellow, Green}; Desi ...

Error: Attempting to display API data in a CardView using NativeScript-Vue results in a TypeError stating that property 'endpoint_link_1' is undefined

Greetings, I am a beginner in NativeScript-Vue and JavaScript. I do not have extensive experience with heavy Javascript coding. I am facing an issue with displaying data fetched from an API in CardViews. Below is the code snippet I attempted: <template ...

Continuously receiving unhandled promise rejection errors despite implementing a try-catch block

Every time I run my code, I encounter the following issue: An UnhandledPromiseRejectionWarning is being thrown, indicating that a promise rejection was not properly handled. This can happen if you throw an error inside an async function without a catch bl ...

Could there be an issue with my website's bootstrap where badges are not being applied properly?

Currently, I am in the process of learning ReactJS and running into an issue where my bootstrap is not working within my .jsx file. Despite following a tutorial (MOSH) diligently and extensively researching on stack overflow, I have not been able to find a ...

How can you convert an epoch datetime value from a textbox into a human-readable 24-hour date format

I have an initial textbox that displays an epoch datetime stamp. Since this format is not easily readable by humans, I made it hidden and readonly. Now, I want to take the epoch value from the first textbox and convert it into a 24-hour human-readable da ...

What is the reason for the return of undefined with getElementsByClassName() in puppeteer?

Currently, I am utilizing puppeteer to fetch certain elements from a webpage, specifically class items (divs). Although I understand that getElementsByClassName returns a list that needs to be looped through, the function always returns undefined for me, e ...

Error in TypeScript when type-checking a dynamic key within a record

When explicitly checking if a property is not a string using a variable key, Typescript throws an error saying Property 'forEach' does not exist on type 'string'. let params: Record<string, string | string[]>; const key = 'te ...

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...