The variable maintains the same value both inside and outside of the loop

I have a list of objects that provide information to a variable, which creates "markers":

var markers = [

//testPOW
{ mesh: ["campDome","POW"],
  color: iconRed,
  location: {lat: 43.30985465943113, lng: 11.898409657895801},
  visible: true,
  id: "TestPOW",
  category: "POW"
},

//testCamps
{ mesh: ["campDome","Camps"],
  color: iconBlue,
  location: {lat: 27.051081239338288, lng: 21.074973750899662},
  visible: true,
  id: "TestCamp",
  category: "Camps"
},

//testInternedCivilians
{ mesh: ["campDome","InternedCivilians"],
  color: iconYellow,
  location: {lat: 47.866084023826794, lng: 2.61794289751219},
  visible: true,
  id: "TestInternedCivilians",
  category: "InternedCivilians"
},
]

The below code creates the markers: //Generate Markers

for ( var i=0; i < markers.length; i++ ) {

    var marker = this.addMarker( {          
        mesh : markers[i].mesh,
        color: markers[i].color,
        color2: 'white',
        location : markers[i].location,
        scale: 0.4,
        offset: 0,
        visible: markers[i].visible,
        id: markers[i].id,
        category: markers[i].category
        
    } );
};

Outside the marker generating loop, the variable marker is like this:

Earth.Marker {options: {...}, object3d: Vn, isMarker: true, earth: Earth, mesh: Array(2), ...}

It represents the last marker generated.

However, inside the loop it appears as:

scripts.js:244 
Earth.Marker {options: {...}, object3d: Vn, isMarker: true, earth: Earth, mesh: Array(2), ...}
scripts.js:244 
Earth.Marker {options: {...}, object3d: Vn, isMarker: true, earth: Earth, mesh: Array(2), ...}
.
.
.

The question is, how can I make the marker variable include all the generated objects even when called outside the loop?

Answer №1

Is it more effective to use an array?

let markerArray = [];

for (var i=0; i < markers.length; i++) {

    markerArray.push(this.addMarker( {          
        mesh : markers[i].mesh,
        color: markers[i].color,
        color2: 'white',
        location : markers[i].location,
        scale: 0.4,
        offset: 0,
        visible: markers[i].visible,
        id: markers[i].id,
        category: markers[i].category
        
    }));
};

Alternatively, could an object be more suitable?


let markerObject = {};

for (var i=0; i < markers.length; i++) {

    markerObject[markers[i].id] = this.addMarker({          
        mesh : markers[i].mesh,
        color: markers[i].color,
        color2: 'white',
        location : markers[i].location,
        scale: 0.4,
        offset: 0,
        visible: markers[i].visible,
        category: markers[i].category
        
    });
};

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 reason behind the failure of executing "this.$refs.inputField.focus()"?

I've set up an input field with a ref="inputField" as shown below: <input ref="inputField"> <button @click="btn">Click</button> When the button is clicked, I want the input field to receive focus. Here& ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

What is the best way to transfer data to another PHP file using AJAX?

Being new to ajax and lacking significant knowledge about it, I have created two PHP files - six.php and six-cuf.php. Upon user input in six.php and submission, this will trigger a call to six-cuf.php using ajax for the calculation. However, while executi ...

Can a variable's value be altered within an array?

I am in the process of developing a software where I encounter a scenario where I need to update the value of an integer that is stored within an array. Here's an example to illustrate my point: int num = 0; int[] nums = new int[] {num}; Console.Wri ...

How can a Chrome extension automatically send a POST request to Flask while the browser is reloading the page?

I am looking to combine the code snippets below in order to automatically send a post request (containing a URL) from a Chrome extension to Flask whenever a page is loading in Chrome, without needing to click on the extension's icon. Is this feasible? ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Trouble with Material-UI's useMediaQuery not identifying the accurate breakpoint right away

While utilizing the MUI useMediaQuery hook in my React app, I encountered a bug that resulted in errors being thrown due to the initial failure of the hook to recognize the correct breakpoint. Eventually, the page re-renders and displays the correct value. ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

Encountering a client component error with the app router in Next.js version 13.4.9

Encountering an error in Nextjs that persists until the 'use client' directive is removed. Warning: Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Con ...

The issue of Rails 4 serving JavaScript as plain text instead of executing it when attempting to utilize AJAX

I am in the process of constructing a basic page layout featuring two side-by-side columns. The left column is intended for user input via a form submission. Upon submitting the form, I want the right column to dynamically update (using AJAX) and display a ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

Find an element within an array in a separate JavaScript file (leveraging AngularJS)

I am new to AngularJS and decided to create a custom map with my own markers that I defined. To do this, I started by creating a JavaScript file containing an array: var myMarkers=[{ method1='..', methode2='..' },{ method1=&a ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

Locating the present URL, dividing it into segments, and verifying the presence of "index.php" within the URL

I'm currently struggling with extracting the current page URL, splitting it into parts, and then checking for the presence of the "index.php" phrase. Here's what I have attempted so far: <?php $domain = $_SERVER['REQUEST_URI']; $val ...

haphazardly showcase circular shapes within a confined space

Is there a way to display circles randomly inside a box without them extending beyond the box or touching its corners? Can the circles be plotted using relative values (percent) within the div? For example, can a circle be placed 10% from the left side and ...

Delivering seamless css integration using express.js

Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me: co ...

Having trouble initiating NPM in a terminal

I keep encountering an issue whenever I try to start NPM using a command in the terminal. Here is the error message that appears: npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark your favorite packages npm ERR! npm stars # Vi ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

Using separate files for routes in Express.js can help organize and streamline your code

I'm facing an issue while setting up a node project where I need to organize my files. Specifically, I want to place a file routes.js within the routes/routes.js directory and controllers files in the controllers/ directory. For instance, let's ...

Transform a group of strings into ObjectId using Mongo, then proceed to delete them

I am currently working with an array of strings containing ids. My goal is to convert these strings into ObjectIds and then use them to delete records from the collection. arrOfStr = ['6346ed8f0c2437c710321c4e','6346ed8f0c2437c710321c4f&apos ...