在我的项目中,我希望阵列每5秒增加一次。我试图使用setInterval来调用函数来执行此操作,但是它每5秒重置一次数组,其数量增加而不是自然增长。有没有一种方法可以增加数量而不必每次都重置阵列?
这些是我用来称呼我的“植物”的功能:
var myPlants = new Array();
var plantSpawn = 0;
function createPlants() {
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants() {
plantSpawn += 5;
for(var i=0; i<plantSpawn; i++){
var rr = Math.round(Math.random() * 150);
var gg = Math.round(Math.random() * 255);
var bb = Math.round(Math.random() * 150);
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'rgba('+rr+','+gg+','+bb+', 1)';
myPlants[i] = plant;
}
}
答案 0 :(得分:1)
执行此操作时,您将明确重置数组的所有值:
for(var i=0; i < plantSpawn; i++){... myPlants[i] = plant; ...}
请注意,plantSpawn
将保留新的数组大小,因此您要遍历所有旧索引以及新索引,然后重新为其分配值。
因此,您可以使用Array.push()通过这种方式向阵列添加5
个新元素:
var myPlants = new Array();
var plantsInc = 5;
function createPlants()
{
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants()
{
// Push N new plants on the array.
for (var i = 0; i < plantsInc; i++)
{
var rr = Math.round(Math.random() * 150);
var gg = Math.round(Math.random() * 255);
var bb = Math.round(Math.random() * 150);
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'rgba('+rr+','+gg+','+bb+', 1)';
// Push a new plant on the array.
myPlants.push(plant);
}
}
作为建议,您甚至可以包装逻辑以在方法内部创建新工厂,如下所示:
var myPlants = new Array();
var plantsInc = 5;
function createPlants()
{
reproducePlants();
setInterval(reproducePlants, 5000);
}
function createPlant()
{
var rr = Math.round(Math.random() * 150);
var gg = Math.round(Math.random() * 255);
var bb = Math.round(Math.random() * 150);
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'rgba('+rr+','+gg+','+bb+', 1)';
return plant;
}
function reproducePlants()
{
// Push N new plants on the array.
for (var i = 0; i < plantsInc; i++)
{
myPlants.push(createPlant());
}
}
答案 1 :(得分:0)
您将覆盖所有现有值,因此不要使用myPlants[i] = plant;
,而是使用myPlants.push(plant)
答案 2 :(得分:0)
您将需要修改函数以将植物添加到现有数组上,而不是循环遍历数组并为其分配新值。
如果您想每5秒向数组添加一个新值,则应该可以执行以下操作:
var myPlants = new Array();
var plantSpawn = 0;
function createPlants() {
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants() {
var rr = Math.round(Math.random() * 150);
var gg = Math.round(Math.random() * 255);
var bb = Math.round(Math.random() * 150);
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'rgba('+rr+','+gg+','+bb+', 1)';
myPlants.push(plant);
}
这只会在数组的末尾添加一个新的工厂,而不是每次调用函数时都将新值分配给当前数组。如果您想一次添加多于1个植物,从这里应该可以将其放入for循环中。循环的每次迭代只会向您的阵列添加一个计划。