使用 ForEach 循环递增值以应用于每个元素

Incrementing value with a ForEach loop to apply on each element

寻求有关数组和增量的帮助。

我有一个函数可以将相同的样式应用于数组中的每个新元素,如下所示。

function SnakeBodyLeft(){
  StorePositions.forEach(BodySnake => {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x)+1 ;
  });
};

// this results in

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1

And so on...

我想编写一个函数来执行如上所示的操作,但将每个新元素的值 +1 递增,并保留第一个元素的初始值。结果会是这样的:

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+3
StorePositions[3] = BodySnake.style.gridColumnStart = (Initial_x + x)+4

And so on....   

我试图让 1 成为一个名为 i 的变量并递增它。但是当我这样做时,i 的增量将应用于数组中的所有元素,而不仅仅是新元素。

let i = 1++;

function SnakeBodyLeft(){
  StorePositions.forEach(BodySnake=> {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x) + i ;
  });
};


//this results in the incremented value being applied to all elements , not just the new ones .

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1

or

StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+2 
StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2
StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+2


基本上,随着索引增长(0,1,2,3...),索引中每个新元素中的值 i 也应增长(0,1,2,3...)。

但我有点卡住了!有人可以帮忙吗?

试试这个

function SnakeBodyLeft(){
  StorePositions.forEach((BodySnake, i)=> {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x) + i;
  });
};

更新 如果您需要从 1 开始递增,则改为这样做:

function SnakeBodyLeft(){
  StorePositions.forEach((BodySnake, i)=> {
    BodySnake.style.gridRowStart = (Initial_y + y);
    BodySnake.style.gridColumnStart = (Initial_x + x) + (i + 1);
  });
};

您可以像这样为 forEach 添加索引 forEach(element, index) => { ... }