为对象元素分配随机值

Assigning Random Values to Object Elements

本文关键字:随机 分配 元素 对象      更新时间:2023-09-26

我正在为对象元素分配 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具有相同的值,但它们不应该不同吗?

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

正在发生的事情是,您正在创建对原始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*/

问题是从 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