问题
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.
我的 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);
如何解决这个问题?
最佳答案
似乎您在 中运行了该函数两次
ctx.drawImage(this,randPos()[0]*32,randPos()[1]*32);
你尝试过这个
ctx.drawImage(this,矩阵[0]*32,矩阵[1]*32);
?
由于matrix
是全局的,因此您可以在setInterval
内部调用它,如下所示
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);
关于JavaScript - Array.prototype.splice 从数组中删除两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30799102/