英文:
How to initialize the array of object
问题
以下是翻译好的代码部分:
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);
}
}
英文:
the following p5js code did not work , since the object in array are reference to the flower , how can i initialize the object with different values ?
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);
}
}
答案1
得分: 1
以下是已翻译的内容:
你可以在将花对象推入数组之前,通过以下三种方法之一取消引用花对象:
行flowers.push(flower);
应更改为
flowers.push(Object.assign({}, flower));
或者
flowers.push({...flower});
或者
flowers.push(JSON.parse(JSON.stringify(flower)));
英文:
You can dereference the flower object before pushing into array by any of following three methods:
line flowers.push(flower);
should be
flowers.push(Object.assign({}, flower));
OR
flowers.push({...flower});
OR
flowers.push(JSON.parse(JSON.stringify(flower)));
答案2
得分: 0
将不同的对象推入数组,而不是一次又一次地更改相同的对象如何?
var flowers = [];
function setup() {
createCanvas(1000, 500);
base_x = width/2;
base_y = height - 50;
for (var i = 0; i < 10; i++) {
// 在每次迭代中创建一个新对象。
// 并且在全局定义此变量没有意义。
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)
)
};
});
英文:
How about pushing distinct objects into the array, instead of changing the same object over and over again.
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);
}
}
or even
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)
)
};
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论