将随机值分配给对象元素

时间:2013-11-10 20:07:24

标签: javascript math random

我将1-50之间的随机值分配给对象元素,我有5个对象,我不知道为什么但所有对象都得到相同的随机值...

这是我的代码:

var SmileyRed = {
   radius: 15,
   xspeed: 0,
   yspeed: 0,
   xpos:350,  // x-position of smiley
   ypos: 65  // y-position of smiley
};

var SmileyReds = new Array();

 for (var i=0; i<5; i++){
 SmileyReds[i] = SmileyRed;
 SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1);
 SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1);
 }

SmileyReds [0] .xspeed和SmileyReds [3] .xspeed具有相同的值,但它们不应该不同吗?

2 个答案:

答案 0 :(得分:3)

问题是从0到4的索引包含对同一对象SmileyRed的引用。如果要分隔它们,则应为每次迭代创建一个新对象。

因此,您实际上是在每次迭代中更改相同的对象。因此,您将始终使用最后一个随机数(来自最后一个对象)。

通过调用返回对象的函数,您将获得每次迭代的新对象。如下所示。

var SmileyRed = function() {
    return {
       radius: 15,
       xspeed: 0,
       yspeed: 0,
       xpos:350,  // x-position of smiley
       ypos: 65  // y-position of smiley
    }
};

var SmileyReds = new Array();

 for (var i=0; i<5; i++){
     SmileyReds[i] = SmileyRed();
     SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1);
     SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1);
 }

<强> JSfiddle

答案 1 :(得分:3)

问题在于,当你使一个对象等于另一个对象时,新对象是对原始对象的引用,而不是副本。

正在发生的事情是你正在为原始的SmileyRed创建5个参考。基本上当你改变一个,你改变所有。因此,只有在循环中应用的值是从循环的最后一次传递开始,前4次传递才会被覆盖。

您可以更改为:

var SmileyReds = new Array();

 for (var i=0; i<5; i++){
/* new object each pass*/
 SmileyReds[i] =  {
   radius: 15,
   xspeed: 0,
   yspeed: 0,
   xpos:350,  // x-position of smiley
   ypos: 65  // y-position of smiley
};
 SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1);
 SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1);
 }

另一种方式是:

var SmileyRed = function(){
    return{
       radius: 15,
       xspeed: 0,
       yspeed: 0,
       xpos:350,  // x-position of smiley
       ypos: 65  // y-position of smiley
    };
}

 for (var i=0; i<5; i++){
    /* new object each pass*/
     SmileyReds[i] =  SmileyRed();/* note () this time*/
相关问题