【问题标题】:How to initialize the array of object如何初始化对象数组
【发布时间】:2020-04-21 17:14:43
【问题描述】:

下面的 p5js 代码不起作用,因为数组中的对象是对花的引用,我怎样才能用不同的值初始化对象?

var flowers;
var flower;

function setup()
{
    createCanvas(1000,500);
    base_x = width/2;
    base_y = height - 50;

    flowers = [];

    flower = {
        base_x: 0,
        base_y: height - 50,
        stem_h: 100,
        col: color(255,50,50)
    }

    for(var i = 0; i < 10; i++)
    {
        flower.base_x = i * 100;
        flower.stem_h = random(50,400);
        flower.col = color(
            random(0,255), 
            random(0,255),
            random(0,255)
            );
        flowers.push(flower);

    }
}

【问题讨论】:

标签: javascript


【解决方案1】:

您可以通过以下三种方法之一在推入数组之前取消引用花对象:

flowers.push(flower); 行应该是

flowers.push(Object.assign({}, flower));

flowers.push({...flower});

flowers.push(JSON.parse(JSON.stringify(flower)));

【讨论】:

    【解决方案2】:

    如何将不同的对象推入数组,而不是一遍又一遍地更改同一个对象。

    var flowers = [];
    
    function setup() {
      createCanvas(1000, 500);
      base_x = width/2;
      base_y = height - 50;
    
      for (var i = 0; i < 10; i++) {
        // Creates a new object in every iteration.
        // And there's no point in defining this variable globally.
        var flower = {
          base_x: i * 100,
          base_y: height - 50,
          stem_h: random(50, 400),
          col: color(
            random(0, 255),
            random(0, 255),
            random(0, 255)
          )
        };
    
        flowers.push(flower);
      }
    }
    

    甚至

    var flowers = Array.from({length: 10}, function(_, i){
      return {
        base_x: i * 100,
        base_y: height - 50,
        stem_h: random(50, 400),
        col: color(
          random(0, 255),
          random(0, 255),
          random(0, 255)
        )
      };
    });
    

    【讨论】:

      猜你喜欢
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2017-02-16
      • 2013-10-12
      相关资源
      最近更新 更多