繁体   English   中英

javascript-数组在日志中显示两个不同的数组

[英]javascript - array displaying two different arrays in logging

对于我的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
   }
}

查看控制台控制台阵列1的照片控制台阵列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函数始终返回传递的元素。 javascript中的对象是通过引用传递 ,因此以后对对象所做的任何更改也将应用于对您存储的对象的所有其他引用。

澄清:

var point1 = new Point(1, 2);
var point2 = pickClose(point1);
// inside pickClose, parameter lastPt = point1:
  lastPt["X"] += dx; // <- this also alters point1!
  lastPt["Y"] += dy; // <- this also alters point1!

因此,如果您想在函数内部返回一个新的 Point (而不更改所传递的Point ),则必须创建一个您要更改并返回的新对象:

var newX = x, newY = y;
// instead of:
lastPt["X"]+=dx;
// do:
newX += dx;

// then, at the bottom, instead of
return lastPt;
// create a new instance
return new Point(newX, newY);

您的pickClose函数将lastPt作为参考,因此您要修改数组中已经存在的Point并再次添加它。

尝试将您的第103行更改为:

var newPt = pickClose(new Point(lastPt.X, lastPt.Y));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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