Reputation: 948
I am trying to remove specific items from an array in javascript, but cannot seem to get the [array].splice function to work.
This code is to be used to check if an SVG object has collided with another (for a game). There are always expected to be 3 objects that the player intersects with, so I wish to remove these from the list.
My code so far is:
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 example of what the console displays for the collisions array is
[<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>]
(copied directly).
However, Google Chrome throws up an error "Uncaught TypeError: collisions.splice is not a function" every time and I do not understand why (or how to fix it).
Upvotes: 1
Views: 1467
Reputation: 2390
According to https://developer.mozilla.org/en/docs/Web/API/SVGSVGElement, result of getIntersectionList
is not an array but NodeList
.
However, you can convert NodeList
to an Array
with following call:
var div_array = Array.prototype.slice.call(div_list); // converts NodeList to Array
More on that here: https://developer.mozilla.org/en-US/docs/Web/API/NodeList
Upvotes: 1
Reputation: 68685
Your collisions
is not of type Array
Try to use
Array.prototype.splice.call(collisions, i, 1)
.
What about splice.call()
see here Function.prototype.call
Upvotes: 4