Why is the output showing as abnormal?

There are occasions when I am unable to successfully execute this script!

var b = [9,8,7,6,5,4,3,2,1]; 
var a = (function(){ 
  var W = []; 
  for(var k in b){ 
    W[W.length] = { 
      index : k, 
      fx : function(){ 
        console.log(k); 
      } 
    } 
  } 
  return W; 
})(); 

console.log(a); 
for(var j = 0; a[j]; j++)a[j].fx();

Why is it not displaying the numerical sequence 987654321 as intended?

Answer №1

Each function you create called fx references the variable k. Instead of saving the current value of k, they only hold a reference to it. As a result, when you execute these functions after the for loop completes, the final value of k is 8, and all functions will output that value.

To prevent this issue and ensure each function has its own variable/value, you can switch from using var k to let k (which is available starting from ECMAScript 6). For more information on let, you can refer to MDN's documentation on let.

var b = [9,8,7,6,5,4,3,2,1]; 
var a = (function(){ 
  var W = []; 
  for (let k in b) { 
    W[W.length] = { 
      index : k, 
      fx : function(){ 
        console.log(k); 
      } 
    } 
  } 
  return W; 
})(); 
 
for(var j = 0; a[j]; j++)
  a[j].fx();

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

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load. In addition to disabling buttons, I also aim to deactivate all links on th ...

JavaScript code to activate a text box when a checkbox is clicked

I have a dynamic table that is generated by JavaScript based on the selected item from a dropdown list. The table consists of a column for checkboxes, a column for displaying names, and a column for inputting quantities. I would like to have all textboxes ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

Updating the material-ui checkbox state to reflect the checked, unchecked, or indeterminate status, can be achieved in reactjs without relying on state

I am currently using Material-UI checkbox components and I have a requirement to programmatically change the state of checkboxes to be checked, unchecked, or indeterminate based on the click of another checkbox. This action needs to be applied to a list of ...

Utilizing $.getJSON to initiate a selection change event

I'm currently working on implementing a feature that involves adding categories to a dropdown list using jQuery Ajax. The goal is to load subcategories when a particular option is selected. However, I've encountered an issue where the addition o ...

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

Switch tabs with JavaScript

I'm encountering an issue with changing tabs using JavaScript and Ajax. The script I have works when not using Ajax but fails to work properly with it. Here is the script: $(document).ready(function(){ $("#mtabs li").click(function() { ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

What is the best way to navigate to a specific location on a web page?

After clicking the "Add comment" link, a comment form popped up using Ajax. I now need assistance with scrolling to it, can you please help me out? ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

JavaScript has encountered an Uncaught TypeError due to an illegal invocation

I am currently developing a lambda function that calls another function with specific parameters. While this code runs without issues in Firefox, it encounters an error in Chrome, displaying a strange message in the inspector: Uncaught TypeError: Illegal ...

How can you confirm the validity of a dropdown menu using JavaScript?

<FORM NAME="form1" METHOD="POST" ACTION="survey.php"> <P>q1: How would you rate the performance of John Doe? <P> <INPUT TYPE='Radio' Name='q1' value='1' id='q1'>1 ...