array.push在forEach循环中不起作用

时间:2019-07-30 18:57:02

标签: javascript arrays node.js

这是我的代码:

let purchasesInfoArray = []

console.log('buyersInfo', buyersInfo)

buyersInfo.forEach((runner) => {
  console.log('runner', runner)

  let purchaseInfo = allPurchase
  let purchaseFunction = {}

  counter = counter + 1;

  console.log('counter é:', counter)

  delete purchaseInfo.friends
  purchaseInfo.priceCents = runner.price
  purchaseInfo.totalTaxPaid = 600
  purchaseInfo.iuguTaxPaid = 198
  purchaseInfo.kmaisTaxPaid = 402
  purchaseInfo.status = 'paid'
  purchaseInfo.runnerCpf = runner.runnerCpf
  purchaseInfo.modality = runner.modality
  purchaseInfo.sex = runner.sex
  purchaseInfo.age = runner.age
  purchaseInfo.birth = runner.birth
  purchaseInfo.buyerName = runner.buyerName

  console.log('número de corredor é:', (oldCounter + counter))

  purchaseInfo.runnerNumber = (oldCounter + counter)
  purchasesInfoArray.push(purchaseInfo)

  console.log('purchase info:', purchaseInfo)
})

console.log(purchasesInfoArray)

为什么我的purchasesInfoArray仅填充了最后一个值?

我的buyersInfo是:

[{ age: 25,
   birth: '15/07/1994',
   buyerName: 'Romário 2',
   kit: 'Básico',
   modality: 'Caminhada',
   price: 60,
   runnerCpf: '012.499.862-32',
   sex: 'man' },
 { age: 25,
   birth: '14/07/1994',
   buyerName: 'Romário 1',
   kit: 'Básico',
   modality: '5 KM',
   price: 60,
   runnerCpf: '012.499.862-30',
   sex: 'man' }]

我的purchasesInfoArray返回两个对象,最后一个对象来自数组。

1 个答案:

答案 0 :(得分:1)

我会将您的代码更改为

let purchasesInfoArray = []
console.log('buyersInfo', buyersInfo)
buyersInfo.forEach((runner) => {
    console.log('runner', runner)
    let purchaseInfo = {...allPurchase} // <-- This line
    let purchaseFunction = {}
    counter = counter + 1;
    console.log('counter é:', counter)
    delete purchaseInfo.friends
    purchaseInfo.priceCents = runner.price
    purchaseInfo.totalTaxPaid = 600
    purchaseInfo.iuguTaxPaid = 198
    purchaseInfo.kmaisTaxPaid = 402
    purchaseInfo.status = 'paid'
    purchaseInfo.runnerCpf = runner.runnerCpf
    purchaseInfo.modality = runner.modality
    purchaseInfo.sex = runner.sex
    purchaseInfo.age = runner.age
    purchaseInfo.birth = runner.birth
    purchaseInfo.buyerName = runner.buyerName
    console.log('número de corredor é:', (oldCounter + counter))
    purchaseInfo.runnerNumber = (oldCounter + counter)
    purchasesInfoArray.push(purchaseInfo)
    console.log('purchase info:', purchaseInfo)
})

要确保每个purchaseInfo是一个新的引用,否则,您只需要更新每个分配的allPurchase,就可以更新每个purchaseInfo,因为它们都共享相同的内存引用。

如果由于JavaScript版本而无法使用传播运算符,则可以选择使用assign方法

let purchaseInfo = Object.assign({}, allPurchase);