【发布时间】:2015-11-22 06:14:13
【问题描述】:
我对我的 javascript 代码中发生的事情感到非常困惑。我正在尝试编写一个函数来创建一个随机点数组。但是,当我在循环内记录数组(其功能是向数组添加点),然后在循环外再次记录它时,我会打印出两个不同的数组。
第一个,如预测的随机 X,Y 点列表,但第二个日志仅包含最后输入的 X,Y 点。
function Pick()
{
var numPoints = 4 * Math.floor(4+Math.random()*5);
var chosen_pts = [];
var lastPt;
for(var i = 0;i<numPoints;i++)
{
if(chosen_pts.length==0)
{
var temp = new Point(Math.floor(Math.random()*250),Math.floor(Math.random()*250));
var newPt = pickClose(temp);
chosen_pts.push(newPt);
lastPt = newPt;
}
else{
var newPt = pickClose(lastPt);
chosen_pts.push(newPt);
}
console.log(chosen_pts[i]); //LINE 106
}
console.log("\noutside of the loop:")
for(var i = 0;i<numPoints;i++)
{
console.log(chosen_pts[i]); //LINE 111
}
}
查看控制台照片 Console Array 1 Console Array 2
编辑:
function pickClose(lastPt)
{
var x = lastPt["X"];
var y = lastPt["Y"];
var dx = 0;
var dy = 0;
var rand = Math.floor(1+Math.random()*100);
if(rand<50){
dx = 1+Math.floor(Math.random()*10);
dy = 1+Math.floor(Math.random()*10);
if( (dx+dy)%3==0 ){
dx*=-1;
}
}
else if(rand<80)
{
dx = 1+Math.floor(Math.random()*25);
dy = 1+Math.floor(Math.random()*25);
if( (dx+dy)%3==0 ){
dy*=-1;
}
}
else{
dx = 1+Math.floor(Math.random()*60);
dy = 1+Math.floor(Math.random()*60);
if( (dx+dy)%4==0 ){
dx*=-1;
dy*=-1;
}
}
if( (x+dx) < 500&& (x+dx) >=0 )
lastPt["X"]+=dx;
else
lastPt["X"]-=dx;
if( (y+dy) < 500&& (y+dy) >=0 )
lastPt["Y"]+=dy;
else
lastPt["Y"]-=dy;
return lastPt;
}
看起来很乱,但本质上我希望根据初始随机数从 for(dx,dy) 中随机选择不同范围的值。
【问题讨论】:
-
pickClose函数似乎是罪魁祸首。请附上它的源代码。 -
考虑到第一次调用
console.log它会为每个点打印不同的数字,我认为这不是问题
标签: javascript arrays syntax duplicates artificial-intelligence