A loop that iterates through only the initial element of an array

When trying to call in the array values using the code snippet below, I encountered an issue. Upon clicking, I am able to successfully retrieve the first material in the array, but then it stops looping through the rest of the materials. Can someone please point out where I might be making a mistake?

var White = new THREE.MeshPhongMaterial( {
            color:0xf6daa5,
        //  specular: 0x000000,
            roughness: 0.7,
            shininess: 0,
        //  bumpMap: mapHeight,
            bumpScale: 12,
            emissive: null,
            emissiveIntensity : null,
            reflectivity: 0.1
   } );
var sink = new THREE.MeshPhongMaterial( {
     color: 0x224466,
     combine: THREE.MixOperation,
     reflectivity: 0.8,
     side: THREE.DoubleSide,
     shininess: 40,
     reflectivity:0

     opacity:null
   } )
var gold = new THREE.MeshPhongMaterial( {
     color: 0x529dc3,                  
     specular: 0x508fbb,            
     shininess: 60,
     emissive:0x070606,
     reflectivity:0.7,
     opacity:0.8,
     shading: THREE.FlatShading,
     combine: THREE.MultiplyOperation
   } )  // have declared these globally

EventsControls.attachEvent('onclick', function() {
    var colors = [White, sink, gold];
    for (var i = 0; i < colors.length; i++) {
        console.log(colors.length);
        object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {

                if (child.material.name == "w__") {

                    child.material = colors[i];
                }
            }
        })
    }
});

Answer №1

Indexes in arrays start at 0 while you seem to be starting at 1.

// Used filler code to make this work
var THREE = {
  "MeshPhongMaterial": function() {},
  "MixOperation": null,
  "DoubleSide": null,
  "FlatShading": null,
  "MultiplyOperation": null
};

var White = new THREE.MeshPhongMaterial({
  color: 0xf6daa5,
  roughness: 0.7,
  shininess: 0,
  bumpScale: 12,
  emissive: null,
  emissiveIntensity: null,
  reflectivity: 0.1
});

Check if object is defined anywhere because it might cause an error in the for loop.

Answer №2

Your list contains multiple strings, all of which need to be enclosed in double quotation marks "

EventsControls.attachEvent('onclick', function() {
    var colors = ["Red", "blue", "green"];
    for (var i = 0; i < colors.length; i++) {
        console.log(colors[i]);
        object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {

                if (child.material.name == "color__") {

                    child.material = colors[i];
                }
            }
        })
    }
});

For more information, visit: http://www.w3schools.com/js/js_arrays.asp

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

jqGrid is failing to display basic JSON data properly

As a newcomer to Jquery and Json, I am struggling with binding a JSON object from a RESTful Webservice written in WCF to jqGrid. Despite saving the JSON object as a static file and attempting to bind it to the grid, I realized that the issue does not lie w ...

Verify your identity using Google reCaptcha during Passport authentication

I am currently working on integrating google reCaptcha into my signup form's back-end, which already includes passport authentication. The code I have so far looks like this: app.get('/signup', function(req, res) { // render the ...

Steps for utilizing response data as parameters for useInfiniteQueryHere is how you can make

On the specific page where I am implementing useInfiniteQuery const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery( ['posts', searchState], ({ pageParam = 1 }) => post.search({ . ...

Encountering a JavaScript error in the backend of Joomla 3.2

I am facing an issue with buttons on my Joomla 3.2.3 sites in the backend. The save, edit (material, module, menu...) buttons are not working properly. These sites were deployed using Akeeba Kickstart. Interestingly, everything worked fine on the developme ...

What defines a suitable application of the ref feature in React?

How can the ref attribute be effectively used in React? I understand that it is considered a shortcut that may go against the principles of React DOM, but I want to know the specifics of how and why. I'm currently evaluating if my use case justifies t ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

PHP: How to Return a Multidimensional Array and Separate Variables Simultaneously

I am trying to send a 2D array with multiple individual variables from a PHP script to a JavaScript client using AJAX. Despite many attempts, I haven't been able to figure out how to include additional individual variables (like $var1, $var2, $var3) i ...

Changing a list into a specific JSON format using Python

I've encountered an issue where my output looks like this: List containing a long string ["21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1 ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

Angular response object being iterated through in a loop

I am facing a challenge while trying to iterate through an array containing values that need to be displayed to the user. Despite receiving a response with the data, I am having trouble accessing and looping through the elements of the array using Angular. ...

Upon clicking a button, initiate an Ajax call to retrieve a value from the code behind (aspx.cs) and display it in an input field on the same page

I am a beginner in the world of AJAX and encountering a problem. I need to initiate an AJAX call when a button is clicked. The goal is to send the value of an input field to the code behind page, aspx.cs, and then display the response from that same input ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Retrieve all items on the webpage using the pattern "_ followed by 10 random characters" through JavaScript

On my webpage, there is a table containing table rows in the following format: <tr id="_C15DKNWCSV">text</tr> I am attempting to scan the webpage and extract all table rows that have an id in the format: id="_(10 RANDOM CHARACTERS)" I want ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

A step-by-step guide on integrating PDF.js with Vue 3 and accessing the distribution folder locally

I must clarify that I am restricted from using any vue libraries to preview PDFs; only pure pdf.js and vue 3 are permitted. Utilizing pdf.js for presenting PDF files within my vue 3 project. Inquiring about the ideal folder structure for the project to en ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

What is preventing bots and crawlers from detecting Next.js meta tags?

I'm currently using Next.js with Typescript and MongoDB to retrieve data. I'm encountering difficulties in rendering the page because the crawler is unable to detect the meta tags. For instance, Bing Search Engine claims that Title and Meta desc ...