When defining the index of arrays using a loop, the function will return NaN

I encountered a problem with my project where this function is returning NaN. In the past, I was able to resolve a similar issue by setting a variable equal to 0. However, that solution is not working in this case.

var distanceArray = [
  [0, 62.3, 58.8, 44.6, 33.2],
  [62.3, 0, 37.9, 65.3, 60.1],
  [58.8, 37.9, 0, 40.5, 78.5],
  [44.6, 65.3, 40.5, 0, 77.6],
  [33.2, 60.1, 78.5, 77.6, 0]
]

var route = [0, 1];

function routeFunction() {
  var totalDistance = 0;
  for (var i = 0; i < route.length; i++) {
    totalDistance += distanceArray[route[i]][route[i + 1]];
  }
  return totalDistance;
}

console.log(routeFunction());

Answer №1

Your loop begins like this:

for (let count = 0; count < journey.length; count++)

This indicates that the variable count will range from 0 to journey.length - 1, including both values.

Within the loop, you have the following line of code:

x += distanceArray[journey[count]][journey[count + 1]];

Note specifically the journey[count + 1] part. Since count iterates from 0 to journey.length - 1, count + 1 will vary between 1 and journey.length. Therefore, on the last cycle, you are trying to access journey[journey.length]. This index is out of bounds and will result in undefined.

Consequently, you are essentially calculating

distanceArray[journey[count]][undefined]

which evaluates to undefined. The += operator then coerces this into a Number, leading to the appearance of NaN.

To address this issue, adjust the loop condition so it does not attempt to access elements beyond the array's end. Update the loop header to read as follows:

for (let count = 0; count < journey.length - 1; count++)

Answer №2

The issue arises when

z+= avstandArray[reiserute[i]][reiserute[i+1]];

In the code above, there is an attempt to retrieve a value from the reiserute array at the (n+1)th element, which is undefined. Adding this undefined element to a number will result in a NaN exception. Therefore, it is necessary to adjust the logic.

for (var i = 0; i < reiserute.length; i++) {
if(i!=reiserute.length)
    z+= avstandArray[reiserute[i]][reiserute[i+1]];
else
    z+= avstandArray[reiserute[i]];
}

Answer №3

It seems like the goal here is unclear, but the main issue at hand is as follows:

The variable "reiserute" does not contain any values and is essentially an empty array. Trying to access values at different indexes within this empty array will result in JavaScript returning "undefined".

reiserute[i] ----> undefined

By attempting to find a value using reiserute[i], you are essentially looking for an undefined value. When trying to access a value in an array by index, JavaScript expects that index to be an integer. Since the index evaluates to undefined, JavaScript throws a NaN error - which stands for "NotANumber".

In this case, the output shows as "0" because the array has a length of zero, causing the condition in the first check to fail and preventing the loop from executing.

If the loop were to execute, it would result in an error displaying NaN.

Answer №4

No errors here, the result is simply 0. Due to the initial declaration of var reiserute = [];, the for loop does not iterate at all.

var avstandArray = [
[0, 62.3, 58.8, 44.6, 33.2],
[62.3, 0, 37.9, 65.3, 60.1],
[58.8, 37.9, 0, 40.5, 78.5],
[44.6, 65.3, 40.5, 0, 77.6],
[33.2, 60.1, 78.5, 77.6, 0]
]

var reiserute = [0,1];

function ruteFunction(){
var z = 0;
for (var i = 0; i < reiserute.length; i++) {
    z+= avstandArray[reiserute[i]][reiserute[i+1]];
    console.log(z);
}
return z;
}

console.log(ruteFunction());

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

Is it necessary for me to replicate this function? - jQuery

I have developed a function that creates a transparent information overlay on a current div for a mobile web app. Context: I am using jQTouch, which means I have separate divs instead of loading individual pages anew. $(document).ready(function() { ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

What are some ways to stop the default event action from occurring when a parent HTML element has an event handler attached to it?

I have a bunch of hyperlinks on my webpage that I want to ajaxify so that clicking on a link deletes the associated item. I attached an event handler to a parent container like this: <div id="parent"> <a href='#' data-itemid='1& ...

Show an item in a visual format of a list

Need help displaying a specific object: cars: { number': 1, 'overload': 1,'brand': {'0': {'porsche': [{'price': 10, 'id': 0}],'vw': [{'price': 20, 'id': 1}] ...

Adjusting the Image Width in React to Match Bootstrap Column Width

Exploring the capabilities of the react-image-mapper library, I stumbled upon an interesting feature: the ImageMapper component offers a prop called width, representing the image width in pixels. Integrating this component into my application based on the ...

Preparing a comma-separated string for use in MySQL's WHERE IN clause

I am working with a string that looks like this... 1,2,3,4,5,6 My goal is to transform it into the following format: '1','2','3','4','5','6' This transformation is needed for using in MySQL&ap ...

What is the best approach for managing multiple socket rooms?

I have been working on developing a chat application that supports multiple chat rooms. After watching several tutorials, I have devised a way to handle this. const io = require("socket.io")(http); io.on("connection", (socket) => { ...

Effortlessly sending multiple forms on a single page via POST in Express JS without the need for page refresh

I am creating a new application using ExpressJS and I want to include the following HTML code in a jade file. On one of my pages, I have 4 form buttons: <div class="dog"> <div class="dog_wrapper clearfix"> <div cla ...

Error encountered during Electron installation - Connection reset by peer

Having some trouble installing electron using npm and encountered this error message: https://i.sstatic.net/7tpKt.jpg Any ideas on how to resolve this? ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

How to extract data from a multidimensional array using d3js

I've been experimenting with a d3js donut chart and am currently working on feeding data in from a multidimensional array. Here is the link to my fiddle. When looking at the output of topHoldersArray, I encounter the following structure: { "1":{"add ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

What is the best method for changing a string of JSON data into a JSONArray

Is there a way to convert the given string into a JSONArray format? {"result":{"passion":[{"id":2,"description":"Sushi"},{"id":3,"description":"Dinner"},{"id":4,"description":"Sex"},{"id":5,"description":"Boobies"},{"id":6,"description":"Sleep"},{"id":7," ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

Tips for making a JSON object with a variable amount of properties

I am looking to transform a structure similar to the following: List<String> fields; into JSON format like this: { "field1": "data1", "field2": "data2", "field3": "data3", ... } ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

Adding to and retrieving data from an array

I am relatively new to the world of JavaScript and jQuery, and I have spent the last three days working on a script. Despite my efforts to find a solution by searching online, I have been unsuccessful so far. It seems like my search skills are lacking. My ...