JavaScript error: Cannot use `.splice()` on [array] ("Uncaught TypeError: collisions.splice is not a function")

Struggling to remove specific items from an array in javascript, the [array].splice function seems to be causing issues.
This piece of code is designed to detect collisions between SVG objects (for a game). The goal is to eliminate 3 objects that the player intersects with.
Here's what I have so far:

svg=document.getElementById("canvas");

function checkcollision(){
    var r0=document.getElementById("rhb1").getBoundingClientRect(), r1=svg.createSVGRect(); r1.x=r0.left; r1.y=r0.top; r1.width=r0.width; r1.height=r0.height;
    var collisions=svg.getIntersectionList(r1,null), len=collisions.length;
    console.log(collisions);
    for(i=len-1;i>=0;i--){
        if(collisions[i].id=="renclosure"||collisions[i].id=="cplayer"||collisions[i].id=="rhb1"){
            collisions.splice(i,1);
        }
    }
    console.log(collisions);
    if(collisions.length>0){
        return true;
    }
    else{
        return false;
    }
}

An instance of how the collisions array looks on the console:

[<rect id=​"renclosure" x=​"0" y=​"0" width=​"15360" height=​"8640" class=​"st0">​</rect>​, <circle id=​"cplayer" cx=​"960" cy=​"540" r=​"50" class=​"st1">​</circle>​, <rect id=​"rhb1" x=​"0" y=​"0" width=​"100" height=​"100" class=​"st2" transform=​"translate(910, 490)​ rotate(0 050 050)​">​</rect>​]

(directly copied).
Nevertheless, Google Chrome consistently throws up an error "Uncaught TypeError: collisions.splice is not a function" and troubleshooting this proves perplexing.

Answer №1

Your collisions variable is not an instance of the Array object.

Consider using

Array.prototype.splice.call(collisions, i, 1)
.

Have you tried using splice.call()? You can learn more about it here

Answer №2

As stated on this website, the outcome of utilizing the getIntersectionList function is not an array but rather a NodeList.

Nevertheless, you have the ability to change the NodeList into an Array by using this method:

var div_array = Array.prototype.slice.call(div_list); // converts NodeList to Array

For further information, check out: this link

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

React: Updating a property in an array of objects causes properties to become undefined

My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

What is the best way to make a selected link stand out with a highlight?

I'm having an issue with the code below that is supposed to keep the selected link highlighted, but it only flashes the green color on click. Can someone help me figure out what's going wrong here? #sidebarContent a:active{ background-colo ...

Uncertainty when trying to reference items within an array of pointers

I'm a bit puzzled about how this piece of code results in the output of 10. While I grasp that p represents the address of the initial element in the pointer array, signifying p+1 as the location of the second element in the list. This means that *(p+ ...

Displaying the servlet response within an iframe

This is the content of Content.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> &l ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

employing ajax for handling a form

Currently, I am facing an issue with updating a user's email on a page. The div refreshes upon submission as intended, but the database is not being updated, and I can't figure out why. My layout consists of a single page where clicking a menu l ...

Unable to submit form in Node.js with Express

I am just starting out with node.js and I need help with a sample form to insert values into a database. Below is the code snippet for my test page: <form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencode ...

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

Creating a staggered nested loop in Python using list comprehensions

I have a list of numbers. I am trying to create a list of lists where each inner list contains the absolute difference between each element and the elements that come after it. For example, turning [1, 2, 3] into [[1, 2], [1], []]. In Javascript, this ca ...

Utilize Javascript ES6 to Sort Through Data in a Table

I require assistance with my project using Material UI and React. There are two key implementations that I need: I am looking to create a filtering system for all rows in each column as shown in the attached image. Additionally, I need a button that can a ...

Why isn't the transparency feature in graphicsmagick working?

Currently, I am utilizing the graphicsmagick npm package which can be found at https://www.npmjs.com/package/gm. In my attempt to write a piece of code similar to the one below, I am struggling to make it function properly with stream. The image file myimg ...

"Creating eye-catching popup images in just a few simple steps

<div className="Image popup"> <Modal isOpen={modalIsOpen} onRequestClose={closeModal} contentLabel="Image popup" > <img src="../img/navratri-1.png" alt="Image popup" /> <b ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

Ensure at least one checkbox is selected by using jQuery validation

I wrote the code below to select multiple checkboxes and validate that at least one checkbox is selected. The data submission to the database works if I remove onsubmit="return validate_form()". However, I want to ensure that at least one checkbox is selec ...

Sass flex order has no effect on elements that are generated

I encountered an issue with the rendering of SVGs in my project. Currently, they are displayed correctly in desktop mode, but in mobile portrait mode, I need to change the order of one specific SVG element within the row. To achieve this, I decided to use ...

Only one specific SVG tag is affected by the CSS stylesheet

I'm encountering an issue with my web page that has multiple SVG tags. Each SVG tag includes a block of style tags containing CSS styles for the respective SVG element. The problem is that these styles seem to leak into the overall global styles. For ...

Changing the image source dynamically at runtime using JavaScript and jQuery

Is it possible to dynamically change the source of an image using jQuery during runtime? I have set up a jsfiddle to demonstrate my question. I am attempting to load the image specified in the variable $newsrc when a button is clicked. However, I am unsure ...

What is the reason that in jsxgraph, a parabola is not able to be created by connecting five points on a single plane?

I recently encountered an issue while working on a project involving drawing points in 3D space that move according to slider values. Even though the points moved correctly, I faced difficulty in drawing a conic section (specifically a parabola) through th ...

Troubleshooting Vue.js: Overutilization of EventBus causing repeated function calls

I'm in the process of implementing an 'undo delete' feature. To achieve this, I am utilizing an Event Bus to broadcast an event to two separate components as shown below: Undo.vue: EventBus.$emit(`confirm-delete-${this.category}`, this.item ...