What is the reason for the undefined status of my variable "j"?

I am working on coloring my 3D object using Three.js. I have a variable called j. When I use alert(j), it works fine. However, when I try to use the variable as an index in my array (colormap), it doesn't work.

colormap=[[0,0,0.5625],[0,0,0.625],[0,0,0.6875],[0,0,0.75],[0,0,0.8125],[0,0,0.875],[0,0,0.9375],[0,0,1],[0,0.0625,1],[0,0.125,1],[0,0.1875,1],[0,0.25,1],[0,0.3125,1],[0,0.375,1],[0,0.4375,1],[0,0.5,1],[0,0.5625,1],[0,0.625,1],[0,0.6875,1],[0,0.75,1],[0,0.8125,1],[0,0.875,1],[0,0.9375,1],[0,1,1],[0.0625,1,0...

j = 0;// index of color in the matrix

var callbackMale = function ( geometry, materials ) 
{
  // surf contains surface
  var cmin=surf.min(), cmax=surf.max(), colorLength=colormap.length;

  for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) 
  {

     var face = geometry.faces[ i ];
     j = Math.round(((surf[i]-cmin)/(cmax-cmin)*colorLength));

     if(j < 0) 
      j=0;
     else if( j >= colorLength) 
       j=colorLength;
     alert(j)
     var ind = colormap[j]; // issue with j being undefined              
     for(var k = 0 ; k < 3 ; k++)
     {              
       face.vertexColors[ k ] = new THREE.Color().setRGB(ind[0],ind[1],ind[2]);                 
     }//end of inner loop

  }//end of outer loop
}

Answer №1

Can you clarify the data type of variable j? Is it an integer, float, or something else? My assumption is that you attempted to assign a float value to an integer variable, resulting in an error.

Answer №2

If your loop exceeds the bounds of the array, it will result in undefined values being returned from colormap[j].

else if( j >= colorLength) 
    j=colorLength;

This pushes your value just beyond the array's limits, as arrays start at zero. To correct this, adjust the maximum to be one less:

else if( j >= colorLength) 
    j=colorLength-1;

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

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

Properly showcasing commas

Need help adding commas to numbers. Currently, my output is 1,2,3,4,5,6,7,890 but I want it to be 1,234,567,890. I am using keyup which is causing some problems. Any suggestions? numberWithCommas : function () { var target = $("#foo"); target.val(targ ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

The Three.js Texture Loader is having difficulty loading a texture

My current challenge involves loading an image using three.js, aiming for a similar result to this project: https://github.com/brunoimbrizi/interactive-particles. However, upon running the project, I am encountering an error instead of successfully loading ...

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

Having difficulty assigning an argument to an HTTP get request in AngularJS

I am new to working with AngularJS and I am attempting to pass an integer argument to an HTTP GET request in my controller. Here is a snippet of my code: (function() { angular .module('myApp.directory', []) .factory('Ne ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

How to Implement Button Disable Feature in jQuery When No Checkboxes Are Selected

I need help troubleshooting an issue with a disabled button when selecting checkboxes. The multicheck functionality works fine, but if I select all items and then deselect one of them, the button disables again. Can someone assist me with this problem? Be ...

Creating a navigation bar that stays fixed at the top of

Hey there, currently I am utilizing a combination of jquery and css to affix my navigation menu at the top when scrolled. However, the problem is that my navigation menu is positioned beneath a div with a height set in viewport units (vh). The jquery scr ...

The NextJS route handler successfully loads when accessed directly through the browser's search bar, but fails to function properly when attempting to console log it

Essentially, I am attempting to retrieve JSON placeholder data by using my route handler that is defined in /api/posts/route.js export async function GET() { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = ...

The webpage containing the authRequired meta briefly flashes on the screen, even if there are no active login sessions on Firebase

As a beginner in Vue and web development, I have been enjoying my journey so far but now I find myself stuck. Currently, I am working on creating an admin dashboard with Firebase authentication. Everything seems to be functioning as expected, except for on ...

I attempted to launch a Node.js application on Heroku, but I'm having trouble sending requests from external routers

After deploying my NodeJS app on Heroku, I encountered a problem. I am able to make a GET request from "/" route that was created in app.js with app.get("/", ...), however I am facing issues with making requests from external routers. The requests seem t ...

Encountering errors preventing the utilization of helpers in fancybox2-rails gem

I've been struggling to implement fancybox2 in my RoR app. I've attempted using the gem and manually adding the files to my assets directory, but I'm having issues with the helpers. Currently, the thumb images generated by the helper are no ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

MongoDB - Error: Unable to access properties of an undefined value (reading 'collection')

The code in indexHelpers.js utilizes functions to interact with the database and perform operations on user details. However, there seems to be an issue where the db.get() function returns null, causing errors when trying to access certain properties. Thi ...

Starting the download of the canvas featuring a stylish border design

I'm facing an issue where the canvas border is not showing up when I download the canvas with a border. The border appears on the screen, but it doesn't get included in the downloaded canvas. let canvas=qrRef.current.querySelector("canvas&qu ...

Executing a callback in AngularJS after multiple HTTP requests have been completed using a forEach loop

I am trying to update multiple items within a foreach loop by sending HTTP requests, and I need a callback once all the requests are complete. Despite searching on Stack Overflow, I haven't found a solution that works for me. Here is the snippet of m ...

Implementing ng-show based on a specific position on a webpage

I am a beginner in AngularJS and I'm struggling to understand how to customize ng-show/ng-hide. I want the navigation bar below to only appear once the user has scrolled 600px down the page, but since I can't use jQuery with Angular, I'm uns ...