Functions do not retrieve values directly from an array

Here is a code snippet that I have

 for(var i=0; i < this.arr2.length; i++) {
      arr.push({
          id: i.toString(),
          label: this.arr2[i],
          display: () => this.arr2[i]
      })
  }

I'm curious why the display is undefined when using the following approach:

let val = this.arr2[i];
display: () => val 

This method seems to be functioning correctly.

Answer №1

In order to declare a block scope local variable, it is recommended to use the let keyword.

for(let = 0; i < this.arr2.length; i++) {
  arr.push({
      id: i.toString(),
      label: this.arr2[i],
      display: () => this.arr2[i]
  })
}

For this scenario, utilizing the map method would be more efficient.

The map() method generates a new array by invoking a provided function on each element in the original array.

arr=arr2.map(function(item,i){
   return {id:i,label:item,display:()=>item};
});

Here's a brief example:

arr2=[1,2,3,4,5];
arr=arr2.map(function(item,i){
       return {id:i,label:item,display:()=>item};
});
console.log(arr[1].display());

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

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Retrieving necessary elements from an array in a MongoDb schema

My goal is to extract only the elements from the notes Array that match the specified tag from the tags array within notes. For instance, I am looking to retrieve notes from the notes Array that have the lrn tag in the tags array, but currently, I am gett ...

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

Unleashing the Power of Lodash Debounce in Vue

Currently, I have integrated debounce from lodash into my main.js file. import lodash from 'lodash' Vue.prototype._ = lodash I've been utilizing it like this._.find(...), and everything has been functioning smoothly. However, when attemptin ...

What is the best way to showcase a PHP variable on a webpage using a JavaScript function?

Is there a way to make use of a JavaScript function (triggered by a button "click event") in order to showcase a PHP variable on my webpage? When I utilize a direct text string in my function, everything works perfectly fine. However, if I swap that text ...

Emphasize the text based on the content in Angular

database of customers check customer records customer service module access service details component for user details display view user details component 1 view user details component 2 template file for user details component see HTML template Seek ...

Error message: Trying to access a string as if it were an array - detrimental outcome imminent

While working on my foreach loop, I encountered the following error: Fatal error: Cannot use string offset as an array [..] on line 97 88. foreach ($response as $result) { 89. if($result['provider'] == 'Facebook') { 90. ...

Is it possible to achieve the full image when utilizing double buffering for drawing on canvas?

I have a code where I am using two canvas elements to draw an image in order to prevent flickering. However, I am facing an issue where I cannot get the full image to display when using this method. When I use just one canvas, the image displays fine. It ...

Vue.js component communication issue causing rendering problems

When it comes to the Parent component, I have this snippet of code: <todo-item v-for="(todo, index) in todos" :key="todo.id" :todo="todo" :index="index"> </todo-item> This piece simply loops through the todos array, retrieves each todo obj ...

Combining Lodash and Mongoose for efficient data merging

Here is a snippet of code that demonstrates an update method using express.js and mongoose. The goal is to combine the existing MongoDB entity with the JSON object provided in the request payload. exports.update = function(req, res) { if(req.body._id) ...

The Swiper slider is unable to display several views at once in the slider layout

I recently started using the amazing swiper slider plugin available here My goal is to replicate the demo-no-210 from that repository. Here is the code snippet I am working with: index.html <!DOCTYPE html> <html> <head> <meta ...

What is the process for selecting and clicking a specific div with a distinct class name in HTML

Hey there! I'm a beginner at coding with puppeteer and I have a question. How can I make my code click on this image: (image) The current code I have looks like this: const puppeteer = require('puppeteer'); (async () => { const bro ...

How to refine a schema by applying filters from another schema

I am working with 2 different Schemas const mongoose = require('mongoose'); const Schema = mongoose.Schema; const {ObjectId} = mongoose.Schema; const matchList = new Schema({ user:[{ type: ObjectId, ref:'User' } ...

Deploying an Azure Blob Trigger in TypeScript does not initiate the trigger

After successfully testing my Azure function locally, I deployed it only to find that it fails to trigger when a file is uploaded to the video-temp container. { "bindings": [ { "name": "myBlob", "type&qu ...

Can one showcase a php content using an ajax event?

I’m having trouble asking the right question because I’m not sure what I’m doing. I have a form that includes a default PHP script that creates three different lines: <form method="GET" name="NewDeliveryNote" action="ItemPosts_INSERT.php"> < ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

The Javascript code compiled in Rails 5 is only functioning on the production environment

I have a JavaScript snippet that is supposed to add a specific class to all images within a container with a certain class: $(document).on('turbolinks:load', function() { $('.blog-article img').addClass('img-fluid'); }); Th ...

What causes the variable to be undefined in the method but not in the constructor in Typescript?

I am currently working on an application using AngularJS 1.4.9 with Typescript. In one of my controllers, I have injected the testManagementService service. The issue I'm facing is that while the testManagementService variable is defined as an object ...