尝试在JavaScript中复制引用传递行为:如何适当地修改我的代码

Trying to replicate pass-by-reference behavior in JavaScript: How to modify my code appropriately

本文关键字:何适当 代码 我的 修改 JavaScript 复制 引用      更新时间:2023-09-26

所以我有两个函数,我希望它们能一起工作,在div周围反弹一个对象。我使用的是图形库,所以下面会有一些不熟悉的代码。我想你仍然会理解我要做的事情的要点

function homepage_screensaver()
{
    /*
        Create Raphael object in the space of the div with id "homeandidiv"
    */
    var pappos = $("#homeanidiv").position();  
    var papx = pappos.left;
    var papy = pappos.top;
    var papheight = $("#homeanidiv").height();
    var papwidth = $("#homeanidiv").width();
    var paper = Raphael(papx, papy, papwidth, papheight);
    /*
        paper: space in which the circle will be bound
    */
    var circx = Math.floor(Math.random() * Number.MAX_VALUE) % papwidth;
    var circy = Math.floor(Math.random() * Number.MAX_VALUE) % papheight;
    /*
        circx, circy: initial positions of circle on the paper
    */
    var mycirc = paper.circle(circx, circy, 10);
    mycirc.attr("fill","#F9C624");
    var theta = Math.floor(Math.random() * Number.MAX_VALUE) % 4 + 1; 
    /*
        theta = 1 <---> object moving at a 45-degree angle
        theta = 2 <---> object moving at a 135-degree angle
        theta = 3 <---> object moving at a 225-degree angle
        theta = 4 <---> object moving at a 315 degree angle
    */
    var circwrapper = new Array(mycirc, theta);
    window.setInterval(function() { move_obj(circwrapper, papwidth, papheight);}, 100);
}
function move_obj(obwrap, backwidth, backheight)
{
     var ob = obwrap[0]; // object 
     var th = obwrap[1]; // theta, the current direction of the object
     var BB = ob.getBBox(); // bounding box for object
     var dx = 0;
     var dy = 0;
     if (BB.x >= backwidth && (th == 1 || th == 2)) 
            dx = -1;
     else if (BB.x <= 0 && (th == 3 || th == 4))
            dx = 1;
     if (BB.y >= backheight && (th == 2 || th == 3))
            dy = -1;
     else if (BB.y <= 0 && (th == 1 || th == 4))
            dy = 1;
     ob.transform("T " + dx + ", " + dy);
     if (dx == 1 && dy == -1)
        th = 1;
     else if (dx == 1 && dy == 1)
        th = 2;
     else if (dx == -1 && dy == 1)
        th = 3;
     else // (dx == -1 && dy == -1)
        th = 4;
     obwrap[0] = ob;
     obwrap[1] = th;
}

以下是我在测试页面后意识到的问题:我的函数move_obj(...)实际上并没有影响我传递给它的第一个参数

  obwrap[0] = ob;
  obwrap[1] = th;

表示我正在尝试实际修改作为第一个参数传入的数组的值。

我的问题有什么"快速解决办法"吗?我宁愿不回去尝试把事情变成全局变量。

正如你所知,我研究了JS中的引用传递问题,这里说数组是通过引用传递的:http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/.所以我看不出这里出了什么问题。

您必须在"move"函数返回后进行重新分配。

window.setInterval(function() {
  var wrapper = [mycirc, theta];
  move_obj(wrapper, papwidth, papheight);
  mycirc = wrapper[0];
  theta = wrapper[1];
}, 100);

将新值分配给数组有效,但它只影响数组。构建数组时,您正在对这两个变量的值进行复制。数组槽和变量之间没有后续的隐式关系,因此对数组的更改对自变量的值没有影响。