Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could this be related to this.nodes.splice(i,1) after removing all values?

var Graph = function(){
   this.nodes = [];
   this.edges = {};
};

Graph.prototype.addNode = function(node){
  this.nodes.push(node);
  this.edges[node] = {};
};

Graph.prototype.contains = function(node){
 for(var i = 0; i < this.nodes[i].length; i++){
    if(this.nodes[i] === node){
      return true;
    } else {
      return false;
    }
  }
};

Graph.prototype.removeNode = function(node){

    for(var key in this.edges){
        if(key === node){
          delete this.edges[node];
        }
    }

    for(var i = 0; i < this.nodes.length; i++){
        if(this.nodes[i] === node){
            this.nodes.splice(i,1);
        }
    }

};

var a = new Graph();
a.addNode("cats");
a.addNode("dogs");
a.contains("cats");
a.removeNode("dogs");
a.contains("cats");
a.removeNode("cats");
a.contains("cats"); //TypeError: Cannot read property 'length' of undefined

Answer №1

You should make a modification

for (var i = 0; i < this.nodes[i].length; i++)

replace it with

    for (var i = 0; i < this.nodes.length; i++)

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

Extract specific elements from an array using Mongoose's $slice operator while still maintaining the

Currently, my task is to retrieve the total number of items in my News object and return a portion of those items as objects. While I have successfully implemented the $slice operator in my query, I am struggling to determine the original array size of the ...

Issue with the iOS gyroscope detected when rotating specifically around the z-axis

I am facing a unique challenge with an unusual bug and I'm looking for help from anyone who has encountered this issue before or can provide a solution. My current project involves using Javascript to access the gyro on iOS devices, specifically focu ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

What is the best way to skip certain steps within a Promise using Bluebird?

Here is an example of some code: Queues.findOne({_id: id}) .then(function(q) { var status = q.status; //... }).then(function(q) { // A }).then(function(q) { // B }).then(function(q) { // C }).then(function(q) { // D }).then(function(q) { // E }).then ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

When running `grunt serve: dist`, an error is thrown stating: "Unknown provider: utilProvider <- util <- NavbarController"

I am facing a problem with my angularJS website that is built using the yeoman angular-fullstack generator. When I run grunt serve, everything works perfectly fine. However, when I try to run grunt serve:dist, I encounter this error: grunt serve: dist -&g ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

What is the reason for triggering a rerender when there is a modification to a map() element using document.querySelector() in JS/next.js?

const slides = [ [string1, string2, stringi], [string1, string2, stringi], [string1, string2, stringi], [string1, string2, stringi], ]; const changeSlide = (num) => { const discipline = document.querySelector("#changeSlide-&quo ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

Error: Unable to simplify version range

Attempting to follow the Express beginner's guide. I created an app and executed npm install as per the provided instructions. > npx express-generator --view=pug myapp > npm install npm ERR! semver.simplifyRange is not a function npm ERR! A com ...

I am looking to adjust the height of my MUI Grid component

Recently exploring React, and I'm looking to set a height limit for MUI Grid. I've structured my project into 3 sections using MUI grid components. My goal is to restrict the page height in order to eliminate the browser scrollbar. If the conten ...

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

What tools do Sketchfab and Thangs utilize to display 3D models?

My website functions as a digital library for a particular niche of 3D models. However, I've noticed that the performance on mobile devices when using modelviewer to display glb files is quite poor. Frequently, the page crashes and reloads unexpectedl ...

Here is how you can pass two callback functions to React.cloneElement:

Recently, I encountered an issue where one of the callbacks passed to a child component using React.cloneElement was always present while the other was undefined. Specifically, activeRow was consistently available but deactivateRow remained undefined. I ...