Unable to assign the property 'mark' as undefined

The error message is puzzling as it seems to indicate a problem with setting the 'mark' property of undefined:

TypeError: Cannot set property 'mark' of undefined
at /home/ubuntu/workspace/tests/app.js:194:36
at Layer.handle [as handle_request](/home/ubuntu/workspace/tests/node_modules/express/lib/router/layer.js:95:5)
...

The code snippet causing this error is:

for(var i = 0;i < req.body.numOfMethods;i++)
{
    for(var x = 0;x< numOfParts[i];x++)
    {
        methodsArray[i][x].mark=parts[i][x].mark;
        methodsArray[i][x].content=parts[i][x].content;
    }
}

However, running the debugging code below produces the following output:

numOfParts[i] = 3
numOfParts[i] = 2
numOfMethods = 2
...

This output confirms that methodsArray[i][x].mark is indeed being assigned values properly. Therefore, the source of the error remains unclear.

Here's where the arrays used in the code are defined:

var methodsArray=[[{mark:Number,content:String}]];
    var numOfParts=[req.body.m1parts,req.body.m2parts,req.body.m3parts,req.body.m4parts];
    ...

Answer №1

var methodsArray=[[{mark:Number,content:String}]];
This specific code snippet focuses solely on methodsArray[0][0].

In cases where methodsArray[i][x] (or methodsArray[i]) is accessed, it typically returns as undefined, unless the values of i and x meet very specific conditions. These exceptions are not within the main scope of discussion.

The issue arises when the loop in your test output attempts to access elements other than methodsArray[0][0] and tries to assign a property.

If necessary, elements can be dynamically created during runtime using the following sample code:

var methodsArray = [];
for(var i = 0; i < req.body.numOfMethods; i++)
{
    methodsArray.push([]);
    for(var x = 0; x< numOfParts[i]; x++)
    {
        methodsArray.push({
          mark: parts[i][x].mark,
          content: parts[i][x].content
        });
    }
}

Note that this process should only occur once during the initial creation of methodsArray.

On a separate note, if you are working with Typescript or Flow, type annotations should use : instead of =. For example, it should be written as

var methodsArray:{mark:Number,content:String}[][];
or
var methodsArray:Array<Array<{ mark:number, content:string }>>;
. In Javascript,
var methodsArray=[[{ mark:number, content:string }]];
represents an array structure containing one element - an array with a single object holding properties mark assigned to the Number constructor and content assigned to the String constructor.

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

How to Animate an Object's Rotation Gently using React Three Fiber App and Use Cannon Library?

I am currently working on a project to create a Tetris-like game using React app, react-three-fiber, and use-cannon. I would like to implement a feature where objects/meshes rotate smoothly when clicked. How can I achieve this? Here is the code for the ob ...

What is the method for setting a lone check_box in formtastic when utilizing Mongoid?

In my model field :resizable, type: Boolean, default: true Experiments with formtastic: = f.input :resizable, :as => :check_boxes # This results in two checkboxes = f.input :resizable # This creates an input field = f.input :resizable, :as => :che ...

Exported excel files cannot contain multiple footer rows in Datatable

Currently, I'm working on creating a Datatable Excel file that can support multiple footers along with an export option. However, I've run into an issue where the footer is only being generated in a single cell without support for multiple lines ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

In Promise.race(), what is the fate of promises that don't come out on top

Promise.race(promise1, promise2, ...) function returns a promise that resolves or rejects based on the fastest promise from the input list. But what happens to the promises that do not win the race? My experiments with Node.js suggest that they keep runn ...

Best practices for implementing $group pipeline Mongodb Aggregation with $dateToString?

I am currently working with Mongodb version 3.0 and I need to utilize $dateToString in a specific format, such as Thu 10-Nov-2016. Below is the code snippet I have: collection.aggregate([ { $group: { _id: { mont ...

Vows.js: Utilizing data from parent topics in nested topics

Is there a way to access the return value of an outer topic from within a test in an inner topic? To clarify, consider this example: "build.css" : { topic : function(file) { fs.readFile(fixtures + "/public/build.css", "utf8", this.callback); }, ...

Divide the string and place each divided part into an array

Let's say we have a string stored in a variable called str, which looks like this: var str = {"data": ["$GPRP,1B2A956ABDF6,AC83F3D44470,-83,1EFF060001092002D9323D6A81154B1BB21D82FB817B1267D51CDD914EEBE7", "$GPRP,0D5B196F34D4,AC83F3D44470,-81,1EFF0600 ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

What design pattern serves as the foundation for Angularjs? Is mastering just one design pattern sufficient?

Although I have been teaching myself Angular and can understand how to code in it, I realize that simply learning the concepts of AngularJS and coding or tweaking things to solve problems is not enough. Moving forward, my goal is to write effective and sta ...

What is the process for preventing the execution of APIs in Postman?

Currently, I am incorporating node js on my server side and I am in need of restricting the API from running on postman or any other platform besides a browser. Perhaps implementing a policy could be the solution, however, I am uncertain about how to go ...

Unable to connect Dropzone to dynamically loaded DIV using AJAX

Using Dropzone for client-side image uploads has been a breeze. Take a look at this basic example that is currently up and running: If you examine the source code, you'll notice that I am utilizing JQuery to connect Dropzone to the upload1 div ID. H ...

JS/Chrome Extension: Ways to Verify if a User is Currently Logged In

After building a Chrome extension, I am now looking to seamlessly integrate it with my existing PHP-based website. This website allows users to have their own accounts and save their favorite items, similar to a Pinterest platform. My main question is whe ...

Streaming data from MongoDB to a file using Node.js

Having recently delved into the world of javascript/node.js, I am attempting to accomplish a basic task: connect to MongoDB, convert the JSON response to CSV format, and then write it to a file. My current approach is outlined below: fs = require('fs ...

Retrieving User Input for Column Filters in AG-Grid-React

After the user enters input in the column filter, I am attempting to update the Redux mode, but it does not seem to be working properly. <AgGridReact rowData={rowData} columnDefs={columnDefs} defaultColDef={defaultColDef} animateRows={ ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...

When you encounter an open response and need to resend it, simply click the "Send Again

After the discontinuation of Firebug, I find myself in need of two crucial functionalities that I used frequently. To replace these features, I am wondering if there are similar options available within the default Firefox Web Console. Previously, when ma ...

What is the best way to use Python and Selenium to click on an angularjs link by comparing it to the text entered by the user?

A user can input a specific link that they would like to click. For example, if the user inputs "Tampa Bay Downs" for the variable track. In my Python Selenium test program, I will search for the following code: <a ng-click="updateFavorite()(raceInfo. ...

Difficulty obtaining elements in Internet Explorer, however works fine in Chrome and Firefox

My <textarea> is set up like this: <textarea class="form-control notetext" id="{{this._id}}-notetext" name="notetext">{{this.text}}</textarea> I am using ajax to send data and load a partial webpage. After loading the content, I attemp ...

The setAttribute method does not function with getElementByClass()

Can someone please help me understand why this code is not working for me: document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);'); I have confirmed that I do indeed have an eleme ...