Please explain the purpose of the .forEach statements listed below

Describe the functionality of the two forEach loops provided in the code snippet below. Also, is 'col' a predefined property for arrays?

var width = data.length, height = data[0].length;
    data.forEach(function(col){
    col.forEach(function(val){
        geometry.vertices.push(new THREE.Vector3(val.x,val.y,val.z))
        colors.push(getColor(2.5,0,val.z));
    });
    });

In case you need to reference the initial code:

var data = new Array();
    for(var x=BIGIN;x<END;x++){
    var row = [];
    for(var y=BIGIN;y<END;y++){
        z = 2.5*(Math.cos(Math.sqrt(x*x+y*y))+1);
        row.push({x: x, y: y, z: z});
    }
    data.push(row);
    }

Answer №1

Array.forEach is a method that loops over an array, similar to a for loop.

array.forEach(function( indice ) {});

data consists of an array of arrays, where col is the parameter passed from the first forEach function, allowing the second forEach to loop through arrays within data.

This structure is evident in the code that generates data

var data = []; // data is an array
...
var row = [];  // row is an array
for(var ...){
    // do stuff
}
data.push(row); // inserts one array inside another

Subsequently, it is iterated as follows:

data.forEach(function(col){ // <- col is passed as the parameter
    col.forEach(function(val){
        // do stuff
    });
});

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

Toggle visibility (individually duplicating) one thousand sentences while maintaining optimal browser and host performance

I have created JQuery scripts to toggle the display of future sentences on my page (approximately 1000 duplicates) and I am seeking the most efficient method (for browser/host) to accomplish this task. Here are two functional solutions that I have already ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...

Using Commas to Separate ChartJS Data Points

I am having trouble formatting numbers in a ChartJS graph to include commas. For example, my data points are currently displayed as 1032.05, 4334.75, 8482.46 but I need them to show as 1,032.05, 4,334.75, 8,482.46. If you would like to see the current cod ...

Guide on how to execute an API request prior to rendering a component in React JS

export default function Dashboard(){ useEffect(() => { setTimeout(()=>console.log("API Call Completed"),5000) },[]) return( <div> <h1>Dashboard</h1> </div> ...

Displaying data as a JSON object in AJAX requests within Grails

I am looking to automatically populate employee details when an employee number is entered. Within the controller, I am executing a method that returns a JSON object: Gson gson = new Gson(); System.out.println(gson.toJson(objEmp)); return gso ...

The model `user` does not have a primary key attribute specified. It is required for all models to have a primary key attribute defined

I have defined a waterline model below: var Waterline = require('Waterline'); var bcrypt = require('bcrypt'); var User = Waterline.Collection.extend({ identity: 'user', datastore: 'myMongo', autoPK: false, attribut ...

Tips for deactivating data monitoring in a Vue.js component attribute

Looking to develop a Vue.js component that accepts properties from its parent component, like this example: <table-cell :value="foo" format="date" /> Although value and format are set as properties, Vue automatically sets up obse ...

There seems to be an issue with accessing the / endpoint in node

https://i.sstatic.net/ROGhJ.png index.js const path = require("path"); const express = require("express"); const exp = require("constants"); const dotenv = require("dotenv").config(); const port = process.env.PORT || 5001; const app = express(); //enabl ...

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Issue with React Native, incapable of modifying value

Having trouble updating the title value in my code. It's not updating as expected. Can someone kindly assist in figuring out what's causing the issue? class EditScreen extends Component { render() { return ( <KeyboardAvoidingView ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

Node.js and MongoDB Login Form Integration with Mongoose

I am relatively new to web development and currently working on a simple web page for user login authentication. My goal is to verify user credentials (username & password) on the LoginPage from a mongoose database, and if they are correct, redirect them t ...

Modify the second dropdown list using Jquery when the first dropdown list changes

I have encountered an issue with using two dropdown lists. Specifically, I am trying to implement a feature where if the user selects the option "2" in the first dropdown list, a script should be executed. Here is the script: $('select[name="servic ...

The python-pyinstrument is in need of a javascript dependency that seems to

As I attempt to profile my Python program using pyinstrument, I encounter an error when trying to view the profile in HTML format. Traceback (most recent call last): File "/home/ananda/projects/product_pred/025200812_cpall_ai_ordering_model_v2/.venv ...

What is causing the most recent iPhones to have issues with my Javascript code?

After analyzing my webserver logs, it appears that an iOS 14 device is categorizing one of my Javascript files as "injected". This file seems to be operating in a separate environment or namespace. As a result, any AJAX attempts made by the script fail bec ...

Conceal or reveal form elements based on input selection

In my current HTML form generated by PHP, I have multiple instances of the following structure: function show(elem, show){ var elements = elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden"); var i; for(i=0; i<eleme ...

What are some techniques for designing a dynamic object that evolves over time in WebGL using Three.js and Tween.js?

Recently, I've started experimenting with Three.js and Tween.js and I'm interested in creating an animation where an object appears to "grow": such as a 3D ball transforming into a tube shape (or being pulled into a tube). Is it possible to achi ...

Guide to displaying radio button value when updating a record

When updating a record in Node.js, I encounter an issue where the values for text input fields are rendered correctly, but the values for radio buttons and textarea in the update form do not appear. Can someone please advise on how to implement this? I am ...

Creating a specialized Angular directive for handling input of positive numbers

I am working on an application that requires a text field to only accept positive integers (no decimals, no negatives). The user should be restricted to entering values between 1 and 9999. <input type="text" min="0" max="99" number-mask=""> While s ...