Javascript array with for loop, returns only last element

前端 未结 2 1808
梦如初夏
梦如初夏 2021-01-01 05:39

I have a for loop, that adds data into an array. but when I console.log the array, it is full of the last item of the for

2条回答
  •  抹茶落季
    2021-01-01 06:33

    You are updating and pushing the same object reference again and again so the object holds the last element values. Instead, initialize the object holding variable inside the for loop beginning.

    for(var i=0; i

    Or directly define the object as the argument of push method without holding it to any variable.

    for (var i = 0; i < ln; i++) {
      materials.push({
        Product: {
          Name: materialsData[i].Product.Name,
          Id: materialsData[i].Product.Id,
        },
        StartingDate: materialsData[i].StartingDate.replace("T00:00:00", "").split('-').reverse().join('-'),
        Device: materialsData[i].Device
      })
    }
    

提交回复
热议问题