简体   繁体   中英

JavaScript - Array.prototype.splice removes two elements from an array

problem

I have a two-dimensional array calles "matrix", in which I added some arrays like this: [x,y]. Now, I want to remove a one element from that array, but the Array.prototype.splice is doing it twice.

My HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <canvas id="mycanvas" width="160" height="160"></canvas>
</body>
</html>

JavaScript

var ctx = document.getElementById("mycanvas").getContext("2d"),
    matrix = [];

for(var m = 0; m<5; m++)
  for(var n = 0; n<5; n++)
    matrix.push([m,n]);

function randPos(){
  var z = Math.floor(Math.random()*matrix.length);
  var m = matrix[z];
  matrix.splice(z,1);
  return m;
}

setInterval(function(){
var m = new Image();
m.src="http://blog.waterrightsimages.com/wordpress1/wp-content/themes/photocrati-theme/images/social/small-facebook.png";
m.onload = function(){
  ctx.drawImage(this,randPos()[0]*32,randPos()[1]*32);
};
console.log(matrix.length);
}, 1000);

How can I fix that problem?

It seems like you run the function twice in ctx.drawImage(this,randPos()[0]*32,randPos()[1]*32); have you tried this ctx.drawImage(this,matrix[0]*32,matrix[1]*32); ?

Since matrix is global, you can call it inside setInterval as follows

 setInterval(function(){
      var m = new Image();
      m.src="http://blog.waterrightsimages.com/wordpress1/wp-content/themes/photocrati-theme/images/social/small-facebook.png";
 m.onload = function(){
   randPos();/*or matrix=randPos();*/
   ctx.drawImage(this,matrix[0]*32,matrix[1]*32);
 };
 console.log(matrix.length);
 }, 1000);

If I did understand correctly, you may try using this method for example:

var cars = 
 [
  ["BMW", "320"],
  ["Mercedes", "E220"],
  ["Dacia", "Logan"],
  ["Dacia", "Duster"],
  ["Ford", "Fiesta"],
  ["Infiniti", "FX30d"]
 ]
cars[4].splice(1,1);
console.log(cars);    

Meaning you will remove from the 5th array (don't forget 0 is the first one) from your array the second element = Fiesta .

It is removing two items because you are calling splice twice:

m.onload = function(){
  ctx.drawImage(this,randPos()[0]*32,randPos()[1]*32);
};

randPos is being invoked twice, which in turn calls splice twice. Instead of trying inline the invocation like that, invoke it once and assign the result to a variable and then get the x/y positions from that variable.

m.onload = function(){
  var pos = randPos();
  ctx.drawImage(this, pos[0]*32, pos[1]*32);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM