The variable was not defined immediately after being assigned a value

Having some trouble with iterating through an array that is assigned to a variable in my code editor. Despite using

console.log(variable_name.length)
and successfully getting the array length, I keep getting an error saying the variable is undefined when trying to iterate through it.

function availableActions(state, reward_matrix) {
  var current_state_row = reward_matrix[state];
  console.log(current_state_row.length);

  let av_act = [];

  for (var i = 0; i < current_state_row.length; i++) {
    if (current_state_row[i] != 0) {
      av_act.push(i);
    }
  }

  return av_act;
}

When running the script, I'm encountering this error:

TypeError: current_state_row is Undefined

This code snippet returns undefined with a series of arrays, possibly causing the issue.

Minimal Reproducible Example (MRE)

function getRand(min, max) {
  let rand = Math.random();
  let number = rand * (max - min) + min;
  number = Math.round(number);
  return number;
}

let total = 0;

let grid = new Array(100)
for(var i = 0; i <100; i++){
  grid[i] = []
  for(var j = 0; j < 10; j++){
    grid[i].push(0)
    total++
  }
}

for (var i = 0; i < 200; i++) {
  let x = getRand(0, grid.length);
  console.log(grid[x]);
}

Answer №1

There is a bug in the code snippet provided, causing it to return undefined during certain iterations of the loop due to an off-by-one error. Using Math.floor instead of Math.round should fix this issue.

It's possible that you are also encountering a similar logic flaw in your code, or the provided example may not accurately represent the problem you are facing.

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

Unraveling a date field from JSON with AngularJS filtering

Extracting data from JSON file shows /Date(1435837792000+0000)/ How can I format the date to appear as Oct 29, 2010 9:10:23 AM? ...

What is the proper way to use AJAX for sending data through a POST request?

Check out my Fiddle Currently, I am in the process of learning AJAX through a tutorial and so far, I have managed to retrieve the desired data and display it on the DOM quite effortlessly. However, I have encountered some difficulties when attempting to ...

Importing a JS class within a Vue.js script tag

I'm attempting to incorporate a JS file into the Vuejs script but for some reason, it's not working as expected. JS file class Errors { constructor() { this.errors = {}; } get(field) { if (_.has(this.errors, 'errors.' + ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

Is there a way to design a side menu navigation bar that reveals items by sliding them out to the right?

Currently, I am attempting to emulate a website as practice since I am relatively new to HTML, CSS, and JavaScript. As part of this exercise, I have designed a navigation bar on the left side (similar to the example provided for food items). The objectiv ...

When attempting to INSERT a JSON Array using the json_to_recordset() function, an error message "Column Does Not Exist" is displayed

Encountering a challenge while attempting to insert variable data from a JSON array into a Postgresql table. The goal is to insert two variables, link_url and link_key, into their respective columns. Utilizing json_to_recordset() method to extract the var ...

What causes the entire DOM to refresh when moving from one route to another?

As I delve into the world of React, I find myself facing a common issue that many have encountered before. Despite searching for solutions high and low, my problem remains unsolved. Beyond just fixing the issue at hand, I am eager to grasp the inner workin ...

Changing a property of an object in Angular using a dynamic variable

It seems like I may be overlooking a crucial aspect of Angular rendering and assignment. I was under the impression that when a variable is updated within a controller's scope, any related areas would automatically be re-evaluated. However, this doesn ...

variable identifier looping through elements

I'm attempting to assign a dynamic ID to my div using ng-repeat. Here's an example: <div id="$index" ng-repeat="repeat in results.myJsonResults"> <div id="$index" ng-click="saveID($index)" ng-repeat="subRepeat in results.myJsonResul ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

What is the process for rendering components in a simulated DOM environment using enzyme?

I am working with a components library and have an interesting challenge. I have created a Tooltip component that renders a tooltip div at the very bottom of the document's body. Now, I want to test whether this div element appears after hovering over ...

What steps can be taken to provide accurate information in the absence of ImageData?

Utilizing a JS library to convert a raster image into a vector, I encountered an issue where the library returned a fill of solid color instead of the desired outcome. I suspect that the problem lies within the ArrayBuffer. The process of loading an imag ...

Ways to define two ng-change functions simultaneously

I am currently working on implementing the phonechange and emailchange functions simultaneously. My goal is to trigger an alert message when both the phone number and email entered are valid. Any assistance from you all would be greatly appreciated! $sc ...

Guide to utilizing PHP for verifying if a variable holds a specific set of characters

I have a variable and I want to use PHP to check if it contains a specific set of characters. I would like the code to look like this: $groupofcharacters = ['$', '#', '*', '(']; if (strcspn($variable, implode(' ...

NodeJs is facing a challenge with the global variable for retrieving all routes methods after successful sign in

I have created a blog page with options for signing up and signing in. I used the req.locals.<name> method Using the GET method. Code snippet from server.js app.get('*',(req,res, next) => { res.locals.user = req.user || null; ...

Could somebody explain in simple terms how to correctly set up offline Google oauth2 with node.js?

When using a web browser, I follow these steps: let { code } = await this.auth2.grantOfflineAccess(); I then store the retrieved code in my database. Next, on the server side with node.js, I do the following: const { tokens } = await oauth2Client ...

Switch up the position of the vertex shader in Three.js/webgl

I've been working on a particle system using three.js that involves using regular JavaScript loops to change particle positions, but I've found that this method is quite slow. Due to this performance issue, I've decided to delve into transf ...

Generate a new NumPy array by performing multiple calculation steps on an existing NumPy array

Here is a 2D numpy array 's' that I am working with: s = np.array([[ 5., 4., np.nan, 1., np.nan], [np.nan, 4., 4., 2., 2.], [ 3., np.nan, np.nan, 5., 5.], [np.nan, 3., 4., 4., np.nan]]) # Creating a new np array ...